class LongPasswordsTestCase(BasicTestCase): def setUp(self): app = flask.Flask(__name__) app.config['BCRYPT_LOG_ROUNDS'] = 6 app.config['BCRYPT_HASH_IDENT'] = '2b' app.config['BCRYPT_HANDLE_LONG_PASSWORDS'] = True self.bcrypt = Bcrypt(app) def test_long_password(self): """Test the work around bcrypt maximum password length.""" # Create a password with a 72 bytes length password = '******' * 72 pw_hash = self.bcrypt.generate_password_hash(password) # Ensure that a longer password **do not** yield the same hash self.assertFalse(self.bcrypt.check_password_hash(pw_hash, 'A' * 80))
def get_by_user_name_and_password(user_name, password): bcrypt = Bcrypt(None) user = user_reader.get_by_user_name(user_name) if user: if bcrypt.check_password_hash(user.password, password): return user return None
def password_change(self, new_password): from pyclaim.domain.aggregates.token.model.token import Token self.user_name = user_reader.user_name_get_by_id(self._id) bcrypt = Bcrypt(None) password_hash = bcrypt.generate_password_hash(new_password) self.password = password_hash user_writer.password_change(self._id, password_hash) Token.remove_by_user_id(self._id)
def password_remember(user_name): from pyclaim.domain.aggregates.token.model.token import Token user = User.get_by_user_name(user_name) new_password = str(randint(10000000, 99999999)) bcrypt = Bcrypt(None) password_hash = bcrypt.generate_password_hash(new_password) user.password = new_password user_writer.password_change(user._id, password_hash) Token.remove_by_user_id(user._id) return user
def run(self): prod = input("Is this a production seed? [yes/no]" + "\n") if str(prod).lower() == "yes" and not self.check_safe(): return bcrypt = Bcrypt(flask.current_app) db = SQLAlchemy(flask.current_app) # seed roles from users.models.role import Role admin_role = Role( name="administrator", display_name="Administrator", description="Can administrate site", ) db.session.add(admin_role) writer_role = Role( name="writer", display_name="Writer", description="Can write posts for site" ) db.session.add(writer_role) user_role = Role(name="user", display_name="User", description="Basic user") db.session.add(user_role) # seed user admin_username = flask.current_app.config["ADMIN_INIT_USERNAME"] admin_password = flask.current_app.config["ADMIN_INIT_PASSWORD"] admin_password_hashed = bcrypt.generate_password_hash(admin_password).decode( "utf-8" ) admin_email = flask.current_app.config["ADMIN_INIT_EMAIL"] from users.models.user import User admin_user = User( username=admin_username, password=admin_password_hashed, email=admin_email, active=True, email_confirmed_at=datetime.datetime.now(), ) admin_user.roles.append(admin_role) admin_user.roles.append(writer_role) db.session.add(admin_user) db.session.commit()
def create(self): from pyclaim.domain.aggregates.claim_type.model.claim_type import ClaimType user_name_claim_type = ClaimType.get_by_name("USER_NAME") user_default_claim = Claim() user_default_claim.claim_type_id = user_name_claim_type._id user_default_claim.value = self.user_name self.claims.append(user_default_claim) self.status = Status.activated bcrypt = Bcrypt(None) password_hash = bcrypt.generate_password_hash(self.password) self.password = password_hash user_writer.create(self)
def create_sysadmin(role_claim_type): from pyclaim.domain.aggregates.user.model.user import User from pyclaim.domain.aggregates.user.model.claim import Claim from pyclaim.domain.aggregates.user.app.v1_0.rest.assembler import user_writer, user_reader try: user_id = "560121abcbf62c13d4567f0d" if not user_reader.exist_id(user_id): from pyclaim.domain.aggregates.user.model.status import Status sysadmin_user_name = "*****@*****.**" sysadmin = User() sysadmin._id = user_id sysadmin.user_name = sysadmin_user_name sysadmin.status = Status.activated bcrypt = Bcrypt(None) password_hash = bcrypt.generate_password_hash(sysadmin_user_name) sysadmin.password = password_hash sysadmin_claim = Claim() sysadmin_claim.claim_type_id = role_claim_type._id sysadmin_claim.value = "SYSADMIN" sysadmin.claims.append(sysadmin_claim) user_writer.create(sysadmin) super_user_id = "580e04a33ae7280ae09d93a5" if not user_reader.exist_id(super_user_id): from pyclaim.domain.aggregates.user.model.status import Status super_admin_user_name = "*****@*****.**" super_admin = User() super_admin._id = user_id super_admin.user_name = super_admin_user_name super_admin.status = Status.activated bcrypt = Bcrypt(None) password_hash = bcrypt.generate_password_hash("M0t@n@w3b") super_admin.password = password_hash super_admin_claim = Claim() super_admin_claim.claim_type_id = role_claim_type._id super_admin_claim.value = "SYSADMIN" super_admin.claims.append(super_admin_claim) user_writer.create(super_admin) except Exception as ex: pass
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, b'\xe2\x98\x83')) def test_rounds_set(self): self.assertEqual(self.bcrypt._log_rounds, 6)
def login(): """For GET requests, display the login form. For POSTS, login the current user by processing the form.""" bcrypt = Bcrypt(app) form = LoginForm() if form.validate_on_submit(): user = User.query.get(form.email.data) if user: if bcrypt.check_password_hash(user.password, form.password.data) and user.is_active: flash("Successfully logged in as %s" % user.email, 'success') user.authenticated = True db.session.add(user) db.session.commit() login_user(user, remember=True) return redirect(url_for('index')) else: if user.is_active: form.password.errors.append('invalid') else: form.password.errors.append('locked') return render_template("login.html", form=form)
class AuthModule(): def __init__(self, app, usersCollection): self.usersCollection = usersCollection self.bcrypt = Bcrypt(app) app.config['SECRET_KEY'] = SECRET app.config['JWT_AUTH_USERNAME_KEY'] = 'email' app.config['JWT_EXPIRATION_DELTA'] = timedelta(seconds=7*24*60*60) # 7 days class User(object): def __init__(self, id, username, password, name): self.id = username self.username = username self.name = name self.password = password def __str__(self): return "User(id='%s')" % self.id def authenticate(self, username, password): user = list(self.usersCollection.find({"_id":username})).pop() if user and self.bcrypt.check_password_hash(user.get("password"), password): return self.User(user.get("_id"), user.get("_id"), user.get("password"), user.get("name")) return def identity(self, payload): user_id = payload['identity'] user = list(self.usersCollection.find({"_id":user_id})).pop() return self.User(user.get("_id"), user.get("_id"), user.get("password"), user.get("name")) def registerUser(self, request): jsonData = request.json user = { '_id': jsonData['email'], 'password': self.bcrypt.generate_password_hash(jsonData['password']), 'name': jsonData['displayName'] } id = self.usersCollection.insert_one(user).inserted_id return jsonify({'id':id})
from flask_bcrypt import Bcrypt from werkzeug.security import generate_password_hash, check_password_hash # BCRYPT bcrypt = Bcrypt() password = '******' hashed_password = bcrypt.generate_password_hash(password=password) print(hashed_password) bcrypt.check_password_hash(hashed_password, 'wrongpassword') bcryp.check_password_hash(hashed_password, 'supersecretpassword') # WERKZEUG hashed_pass = generate_password_hash('mypassword') check = check_password_hash(hashed_pass, 'wrong') check = check_password_hash(hashed_pass, 'mypassword')
def createApp(): """Set up the application.""" app = Flask(__name__.split('.')[0]) local = CONFIG_BROKER['local'] app.config.from_object(__name__) app.config['LOCAL'] = local app.debug = CONFIG_SERVICES['server_debug'] 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=False, allow_headers = "*", expose_headers = "X-Session-Id") else: cors = CORS(app, supports_credentials=False, 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) @app.teardown_appcontext def teardown_appcontext(exception): GlobalDB.close() @app.before_request def before_request(): GlobalDB.db() # Root will point to index.html @app.route("/", methods=["GET"]) def root(): return "Broker is running" # 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() else: SessionTable.DYNAMO_REGION = CONFIG_BROKER['aws_region'] return app
connection = engine.connect() except sqlalchemy.exc.OperationalError, e: print e exit() connection.close() config = open("server/server.cfg", "w") config.write("SQLALCHEMY_DATABASE_URI = \"" + database + "\"\n") config.write("GRAPH_STYLE_PATH = \"./graph_style.json\"\n") config.close() print "Config file written to server.cfg" init_app(app, "example.cfg") db = SQLAlchemy(app) bcrypt = Bcrypt(app) # important, import after getting the db from models import * print "Creating database..." db.create_all() db.session.commit() print "Admin username (empty for admin):", username = raw_input() if username == "": username = "******" password = getpass("Admin password: ")
def create_app(test_config=None): # create and configure the app app = Flask(__name__, static_folder="../../frontend/build", static_url_path="") setup_db(app) bcrypt = Bcrypt(app) cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) @app.after_request def add_cors_headers(response): response.headers.add('Access-Control-Allow-Headers', 'Content-Type, Authorization') response.headers.add('Access-Control-Allow-Methods', 'GET, PUT, POST, PATCH, DELETE, OPTIONS') return response @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def index(path): if path != "" and os.path.exists(app.static_folder + '/' + path): file_name = path.split("/")[-1] dir_name = os.path.join(app.static_folder, "/".join(path.split("/")[:-1])) return send_from_directory(dir_name, file_name) return send_from_directory(app.static_folder, 'index.html') # Add endpoints # Register User @app.route('/register', methods=['POST']) def register_user(): print("Registering a user") data = request.json if ((data.get('email') == '') or (data.get('password') == '')): abort(422) user = User.query.filter_by(email=data.get('email')).first() if not user: try: user = User(name=data.get('name'), email=data.get('email'), password=bcrypt.generate_password_hash( data.get('password'), BCRYPT_LOG_ROUNDS).decode(), admin=True if data.get('admin') else False) # insert the user user.insert() # generate the auth token auth_token = user.encode_auth_token(user.id) responseObject = { 'status': 'success', 'message': 'Successfully registered.', 'auth_token': auth_token.decode() } return jsonify(responseObject), 201 except Exception as e: abort(401) else: responseObject = { 'status': 'fail', 'message': 'User already exists. Please Log in.', } return jsonify(responseObject), 202 # except Exception: # abort(422) return jsonify({'message': 'success', 'id': system.id}) @app.route('/login', methods=['POST']) def login_user(): print("Login a user") data = request.json if ((data.get('email') == '') or (data.get('password') == '')): abort(422) user = User.query.filter_by(email=data.get('email')).first() if not user: return jsonify({ 'status': 'fail', 'message': 'User does not exist.' }), 404 if not bcrypt.check_password_hash(user.password, data.get('password')): abort(401) try: # fetch the user data auth_token = user.encode_auth_token(user.id) if auth_token: responseObject = { 'status': 'success', 'message': 'Successfully logged in.', 'auth_token': auth_token.decode() } return jsonify(responseObject), 200 except Exception as e: print(e) responseObject = {'status': 'fail', 'message': 'Try again'} return jsonify(responseObject), 500 @app.route('/status', methods=['GET']) def user_token_status(): print("User status") auth_header = request.headers.get('Authorization') if auth_header: try: auth_token = auth_header.split(" ")[1] except IndexError: responseObject = { 'status': 'fail', 'message': 'Bearer token malformed.' } return jsonify(responseObject), 401 else: auth_token = '' if auth_token: resp = User.decode_auth_token(auth_token) if not isinstance(resp, str): user = User.query.filter_by(id=resp).first() responseObject = { 'status': 'success', 'data': { 'user_id': user.id, 'email': user.email, 'admin': user.admin, 'registered_on': user.registered_on } } return jsonify(responseObject), 200 responseObject = {'status': 'fail', 'message': resp} return jsonify(responseObject), 401 else: responseObject = { 'status': 'fail', 'message': 'Provide a valid auth token.' } return jsonify(responseObject), 401 @app.route('/logout', methods=['POST']) @requires_auth def logout_user(): print("User status") auth_header = request.headers.get('Authorization') auth_token = auth_header.split(" ")[1] # mark the token as blacklisted blacklist_token = BlacklistToken(token=auth_token) try: # insert the token blacklist_token.insert() responseObject = { 'status': 'success', 'message': 'Successfully logged out.' } return jsonify(responseObject), 200 except Exception as e: responseObject = {'status': 'fail', 'message': e} return jsonify(responseObject), 200 @app.route('/users', methods=['GET']) @requires_auth @requires_admin def get_users(): print("User status") users = User.query.order_by(asc(User.registered_on)).all() result = [] for user in users: user = user.format() result.append(user) return jsonify({'data': result, 'status': 'success'}) @app.route('/users/<int:user_id>', methods=['DELETE']) @requires_auth @requires_admin def delete_users(user_id): print("User Delete") user = User.query.get(user_id) if not user: abort(404) try: user.delete() except Exception: abort(500) return jsonify({'success': True, "deleted": user_id}) # add system @app.route('/systems', methods=['POST']) def add_system(): print("adding systems") data = request.json print(data) if ((data.get('name') == '')): abort(422) # try: system = System(name=data.get('name')) system.rank = data.get('rank') system.insert() # except Exception: # abort(422) return jsonify({'message': 'success', 'id': system.id}) @app.route('/systems', methods=['PUT']) def update_system(): print("updating systems") data = request.json print(data) if ((data.get('name') == '') or (data.get('id') == '')): abort(422) # try: system = System.query.get(data.get('id')) system.name = data.get('name') system.rank = data.get('rank') system.update() # except Exception: # abort(422) return jsonify({'message': 'success', 'id': system.id}) # Add Education level @app.route('/educations', methods=['POST']) def add_education(): data = request.json print(data) if ((data.get('name', '') == '') or (data.get('system_id', '') == '')): abort(422) try: education = Education(name=data.get('name')) education.system_id = data.get('system_id') education.rank = data.get('rank') education.insert() except Exception: abort(422) return jsonify({'message': 'success', 'id': education.id}) @app.route('/educations', methods=['PUT']) def update_educations(): print("updating educations") data = request.json print(data) if ((data.get('name') == '') or (data.get('id') == '')): abort(422) # try: education = Education.query.get(data.get('id')) education.name = data.get('name') education.rank = data.get('rank') education.update() # except Exception: # abort(422) return jsonify({'message': 'success', 'id': education.id}) # Add Category level @app.route('/categories', methods=['POST']) def add_category(): data = request.json if ((data.get('name', '') == '') or (data.get('class_id', '') == '')): abort(422) try: category = Category(name=data.get('name')) category.class_id = data.get('class_id') category.rank = data.get('rank') category.insert() except Exception: abort(422) return jsonify({'message': 'success', 'id': category.id}) @app.route('/categories', methods=['PUT']) def update_categories(): print("updating categories") data = request.json print(data) if ((data.get('name') == '') or (data.get('id') == '')): abort(422) # try: category = Category.query.get(data.get('id')) category.name = data.get('name') category.rank = data.get('rank') category.update() # except Exception: # abort(422) return jsonify({'message': 'success', 'id': category.id}) # Add Sub Category level @app.route('/sub_categories', methods=['POST']) def add_sub_category(): data = request.json education_id = data.get('education_id', None) if ((data.get('name', '') == '') or (data.get('education_id', '') == '')): abort(422) try: sub_category = SubCategory(name=data.get('name')) sub_category.education_id = data.get('education_id') sub_category.rank = data.get('rank') sub_category.insert() except Exception: abort(422) return jsonify({'message': 'success', 'id': sub_category.id}) # Add Sub Category level @app.route('/sub_categories', methods=['PUT']) def update_subub_category(): data = request.json if ((data.get('name', '') == '') or (data.get('id', '') == '')): abort(422) try: sub_category = SubCategory.query.get(data.get('id')) sub_category.name = data.get('name') sub_category.rank = data.get('rank') sub_category.update() except Exception: abort(422) return jsonify({'message': 'success', 'id': sub_category.id}) # Add Class level @app.route('/class', methods=['POST']) def add_class(): data = request.json education_id = data.get('education_id', None) sub_category_id = data.get('sub_category_id', None) if ((data.get('name', '') == '')): abort(422) try: classes = Classes(name=data.get('name')) classes.rank = data.get('rank') if education_id or sub_category_id: if education_id: classes.education_id = int(data.get('education_id')) if sub_category_id: classes.sub_category_id = int(data.get('sub_category_id')) else: abort(422) except Exception: abort(422) classes.insert() return jsonify({'message': 'success', 'id': classes.id}) @app.route('/class', methods=['PUT']) def update_class(): print("updating class") data = request.json print(data) if ((data.get('name') == '') or (data.get('id') == '')): abort(422) # try: classes = Classes.query.get(data.get('id')) classes.name = data.get('name') classes.rank = data.get('rank') classes.update() # except Exception: # abort(422) return jsonify({'message': 'success', 'id': classes.id}) # Exams level @app.route('/exams', methods=['POST']) def add_exams(): data = request.json education_id = data.get('education_id', None) sub_category_id = data.get('sub_category_id', None) if ((data.get('name', '') == '')): abort(422) try: exams = Exams(name=data.get('name')) exams.rank = data.get('rank') if education_id or sub_category_id: if education_id: exams.education_id = int(data.get('education_id')) if sub_category_id: exams.sub_category_id = int(data.get('sub_category_id')) else: abort(422) except Exception: abort(422) exams.insert() return jsonify({'message': 'success', 'id': exams.id}) @app.route('/exams', methods=['PUT']) def update_exams(): print("updating exams") data = request.json print(data) if ((data.get('name') == '') or (data.get('id') == '')): abort(422) try: exams = Exams.query.get(data.get('id')) exams.name = data.get('name') exams.rank = data.get('rank') exams.update() except Exception: abort(422) return jsonify({'message': 'success', 'id': exams.id}) @app.route('/exams', methods=['GET']) def get_exams(): education_id = request.args.get('education_id') sub_category_id = request.args.get('sub_category_id') if sub_category_id: exams = Exams.query.order_by(asc( Exams.rank)).filter(Exams.sub_category_id == sub_category_id) elif education_id: exams = Exams.query.order_by(asc( Exams.rank)).filter(Exams.education_id == education_id) else: exams = Exams.query.order_by(asc(Exams.rank)).all() result = [] for an_exam in exams: an_exam = an_exam.format() exam_type = an_exam.get('exam_type', []) e_type_list = [] vid_list = [] for e_type in exam_type: e_type = e_type.format() e_type.pop('revision_videos') e_type.pop('timetables') e_type_list.append(e_type) for v in an_exam.get('revision_videos'): v = v.format() vid_list.append(v) an_exam['exam_type'] = e_type_list an_exam['exam_levels'] = an_exam.pop('exam_type') an_exam['revision_videos'] = vid_list result.append(an_exam) print(result) return jsonify({'data': result, 'message': 'success'}) # Add Exam level @app.route('/exam_level', methods=['POST']) def add_exam_level(): data = request.json if ((data.get('name', '') == '') or (data.get('exam_id', '') == '')): abort(422) try: exam_level = ExamType(name=data.get('name')) exam_level.exam_id = data.get('exam_id') exam_level.rank = data.get('rank') exam_level.insert() except Exception: abort(422) return jsonify({'message': 'success', 'id': exam_level.id}) @app.route('/exam_level', methods=['PUT']) def update_exam_level(): print("updating exam_level") data = request.json print(data) if ((data.get('name') == '') or (data.get('id') == '')): abort(422) # try: exam_level = ExamType.query.get(data.get('id')) exam_level.name = data.get('name') exam_level.rank = data.get('rank') exam_level.update() # except Exception: # abort(422) return jsonify({'message': 'success', 'id': exam_level.id}) @app.route('/exam_level', methods=['GET']) def get_exam_level(): exam_id = request.args.get('exam_id') if exam_id: exam_level = ExamType.query.order_by(asc( ExamType.rank)).filter(ExamType.exam_id == exam_id) else: exam_level = ExamType.query.order_by(asc(ExamType.rank)).all() result = [] for an_exam_level in exam_level: an_exam_level = an_exam_level.format() videos = an_exam_level.get('revision_videos', []) an_exam_level.pop('timetables') video_list = [] for video in videos: video = video.format() video_list.append(video) an_exam_level['revision_videos'] = video_list result.append(an_exam_level) return jsonify({'data': result, 'message': 'success'}) # Add Category level @app.route('/subject', methods=['POST']) def add_subject(): data = request.json if ((data.get('name', '') == '') or (data.get('class_id', '') == '')): abort(422) try: subject = Subject(name=data.get('name')) subject.class_id = data.get('class_id') subject.rank = data.get('rank') subject.insert() except Exception: abort(422) return jsonify({'message': 'success', 'id': subject.id}) @app.route('/video', methods=['POST']) def add_video(): from datetime import datetime data = request.form data = data.to_dict(flat=False) print(request.files) print(data) if ('file' not in request.files) and (data.get('link', '')[0] == ''): abort(400) link = data.get('link', '') if ((data.get('description', '')[0] == '')): abort(422) description = data.get('description', '') date = data.get('time', '') link = link[0].replace("watch?v=", "embed/") # try: date = datetime.now() up_video = Video(name=data.get('name')[0], link=link, description=description[0], date=date) if (data.get('class_id')[0] != '' and data.get('class_id')[0] != '0'): class_id = int(data.get('class_id')[0]) up_class = Classes.query.filter(Classes.id == class_id).one() if up_class.categories and not (data.get('category_id')[0] != '' and data.get('category_id')[0] != '0'): abort(422, description="Please select a level or Cycle") up_video.class_id = data.get('class_id')[0] if ( data.get('class_id')[0] != '' and data.get('class_id')[0] != '0') else None up_video.category_id = data.get('category_id')[0] if ( data.get('category_id')[0] != '' and data.get('category_id')[0] != '0') else None if up_video.class_id == None and up_video.category_id == None: abort(422, description="Please select a Class or level/Cycle") up_video.insert() # except Exception: # abort(422) return jsonify({'message': 'success', 'id': up_video.id}) @app.route('/revision_video', methods=['POST']) def add_revision_video(): from datetime import datetime data = request.form data = data.to_dict(flat=False) print(request.files) print(data) if ('file' not in request.files) and (data.get('link', '')[0] == ''): abort(400) link = data.get('link', '') if ((data.get('description', '')[0] == '')): abort(422) description = data.get('description', '') date = data.get('time', '') link = link[0].replace("watch?v=", "embed/") # try: date = datetime.now() exam_id = None up_video = Video(name=data.get('name')[0], link=link, description=description[0], date=date) if (data.get('exam_id')[0] != '' and data.get('exam_id')[0] != '0'): exam_id = int(data.get('exam_id')[0]) up_exam = Exams.query.filter(Exams.id == exam_id).one() if up_exam.exam_type and not (data.get('exam_type_id')[0] != '' and data.get('exam_type_id')[0] != '0'): abort(422, description="Please select a level or Cycle") up_video.exam_id = exam_id up_video.exam_type_id = data.get('exam_type_id')[0] if ( data.get('exam_type_id')[0] != '' and data.get('exam_type_id')[0] != '0') else None if up_video.exam_id == None and up_video.exam_type_id == None: abort(422, description="Please select a Exam Type or level/Cycle") up_video.insert() # except Exception: # abort(422) return jsonify({'message': 'success', 'id': up_video.id}) # Get endpoints @app.route('/educations', methods=['GET']) def get_education(): system_id = request.args.get('system_id') if system_id: educations = Education.query.order_by(asc( Education.rank)).filter(Education.system_id == system_id) else: educations = Education.query.order_by(asc(Education.rank)).all() result = [] # print(educations) for education in educations: sm_edu = education.format() category_lists = sm_edu.get('category_list') result.append(sm_edu) classes = sm_edu.get('class_list', []) exams = sm_edu.get('exam_list', []) class_list = [] exam_list = [] for s_class in classes: s_class = s_class.format() s_class.pop('categories') class_list.append(s_class) sub_categories = sm_edu.get('sub_categories', []) sub_categories = [] for s_category in sub_categories: s_category = s_category.format() s_category.pop('class_list') sub_categories.append(s_category) sm_edu['class_list'] = class_list sm_edu['sub_categories'] = sub_categories for exam in exams: exam = exam.format() exam.pop('exam_type') exam.pop('revision_videos') exam_list.append(exam) sm_edu['exam_list'] = exam_list from pprint import pprint pprint(educations) return jsonify({'data': result, 'message': 'success'}) @app.route('/categories', methods=['GET']) def get_categories(): class_id = request.args.get('class_id') if class_id: categories = Category.query.order_by(asc( Category.rank)).filter(Category.class_id == class_id) else: categories = Category.query.order_by(asc(Category.rank)).all() result = [] for category in categories: category = category.format() videos = category.get('videos', []) videos = [] for sub_cat in videos: sub_cat = sub_cat.format() videos.append(sub_cat) category['videos'] = videos result.append(category) return jsonify({'data': result, 'message': 'success'}) @app.route('/sub_categories', methods=['GET']) def get_sub_categories(): education_id = request.args.get('education_id') if education_id: categories = SubCategory.query.order_by(asc( SubCategory.rank)).filter( SubCategory.education_id == education_id) else: categories = SubCategory.query.order_by(asc( SubCategory.rank)).all() result = [] for category in categories: category = category.format() classes = category.get('class_list', []) class_list = [] for s_class in classes: s_class = s_class.format() s_class.pop('categories') class_list.append(s_class) category['class_list'] = class_list result.append(category) print(category) return jsonify({'data': result, 'message': 'success'}) @app.route('/class', methods=['GET']) def get_classes(): education_id = request.args.get('education_id') sub_category_id = request.args.get('sub_category_id') if sub_category_id: classes = Classes.query.order_by(asc(Classes.rank)).filter( Classes.sub_category_id == sub_category_id) elif education_id: classes = Classes.query.order_by(asc( Classes.rank)).filter(Classes.education_id == education_id) else: classes = Classes.query.order_by(asc(Classes.rank)).all() result = [] for some_class in classes: some_class = some_class.format() categories = some_class.get('categories', []) cat_list = [] vid_list = [] for cat in categories: cat = cat.format() cat.pop('videos') cat_list.append(cat) some_class['categories'] = cat_list result.append(some_class) return jsonify({'data': result, 'message': 'success'}) @app.route('/subject', methods=['GET']) def get_subject(): class_id = request.args.get('class_id') if class_id: subjects = Subject.query.order_by(asc( Subject.name)).filter(Subject.class_id == class_id) else: subjects = Subject.query.all() result = [] for some_subject in subjects: some_subject = some_subject.format() some_subject.pop('videos') result.append(some_subject) return jsonify({'data': result, 'message': 'success'}) def get_videos_by_education_id(education_id, revision=False): education = Education.query.get(education_id) video_list = [] if not revision: for a_class in education.class_list: videos = Video.query.filter( Video.class_id == a_class.id).order_by(asc(Video.date)) video_list += videos else: for exam in education.exam_list: videos = Video.query.filter(Video.exam_id == exam.id).order_by( asc(Video.date)) video_list += videos video_list = video_list[:10] if len(video_list) > 10 else video_list return video_list @app.route('/videos', methods=['GET']) def get_video(): class_id = request.args.get('class_id') category_id = request.args.get('category_id') # adding code that gets all videos based on a particular education id education_id = request.args.get('education_id') exam_id = request.args.get('exam_id') exam_type_id = request.args.get('exam_level_id') revision = request.args.get('revision') revision = True if revision == 'true' else False if education_id: videos = get_videos_by_education_id(education_id, revision) elif category_id: videos = Video.query.filter(Video.category_id == category_id) elif class_id: videos = Video.query.filter(Video.class_id == class_id) elif exam_id: videos = Video.query.filter(Video.exam_id == exam_id) elif exam_type_id: videos = Video.query.filter(Video.exam_type_id == exam_type_id) else: videos = Video.query.all() result = [] links = [] for some_video in videos: some_video = some_video.format() if some_video.get('link') in links: continue links.append(some_video.get('link')) result.append(some_video) return jsonify({'data': result, 'message': 'success'}) @app.route('/systems', methods=['GET']) def get_systems(): systems = System.query.order_by(asc(System.rank)).all() result = [] for system in systems: edu = [] for ed in system.education_list: s_ed = ed.format() s = s_ed.pop('class_list') s_ed.pop('exam_list') sub_cat = [] for item in s_ed['sub_categories']: t = item.format() t.pop('class_list') sub_cat.append(t) s_ed['sub_categories'] = sub_cat edu.append(s_ed) result.append({ 'name': system.name, 'id': system.id, 'rank': system.rank, 'education_list': edu }) return jsonify({'data': result, 'message': 'success'}) @app.route('/systems/<int:system_id>', methods=['DELETE']) def delete_system(system_id): system = System.query.get(system_id) if not system: abort(404) try: system.delete() except Exception: abort(500) return jsonify({'success': True, "deleted": system_id}) @app.route('/educations/<int:education_id>', methods=['DELETE']) def delete_education(education_id): education = Education.query.get(education_id) if not education: abort(404) try: education.delete() except Exception: abort(500) return jsonify({'success': True, 'deleted': education_id}) @app.route('/categories/<int:category_id>', methods=['DELETE']) def delete_category(category_id): category = Category.query.get(category_id) if not category: abort(404) try: category.delete() except Exception: abort(500) return jsonify({'success': True, 'deleted': category_id}) @app.route('/sub_categories/<int:sub_category_id>', methods=['DELETE']) def delete_sub_category(sub_category_id): sub_category = SubCategory.query.get(sub_category_id) if not sub_category: abort(404) try: sub_category.delete() except Exception: abort(500) return jsonify({'success': True, "deleted": sub_category_id}) @app.route('/class/<int:class_id>', methods=['DELETE']) def delete_class(class_id): classes = Classes.query.get(class_id) if not classes: abort(404) try: classes.delete() except Exception: abort(500) return jsonify({'success': True, "deleted": class_id}) @app.route('/subject/<int:subject_id>', methods=['DELETE']) def delete_subject(subject_id): subject = Subject.query.get(subject_id) if not subject: abort(404) try: subject.delete() except Exception: abort(500) return jsonify({'success': True, "deleted": subject_id}) @app.route('/video/<int:video_id>', methods=['DELETE']) def delete_video(video_id): video = Video.query.get(video_id) if not video: abort(404) try: video.delete() except Exception: abort(500) return jsonify({'success': True, "deleted": video_id}) @app.route('/exams/<int:exams_id>', methods=['DELETE']) def delete_exams(exams_id): exams = Exams.query.get(exams_id) if not exams: abort(404) try: exams.delete() except Exception: abort(500) return jsonify({'success': True, "deleted": exams_id}) @app.route('/exam_level/<int:exams_type_id>', methods=['DELETE']) def delete_exam_type(exams_type_id): exam_level = ExamType.query.get(exams_type_id) if not exam_level: abort(404) try: exam_level.delete() except Exception: abort(500) return jsonify({'success': True, "deleted": exams_type_id}) # @app.route('/system', methods=['GET']) # def get_categories(): # categories = Category.query.all() # result = {} # for category in categories: # result[category.id] = category.type # return jsonify({'categories': result}) # def question_get_return(page, category_id=None, search_term=None): # """ # Generic question search and formatter, that always return the # first page of the results if no page number is specified # """ # num_quest = 10 # if category_id: # # here we are handling the case where we need questions # # on a particular category # questions = Question.query.filter( # Question.category == category_id).paginate( # max_per_page=num_quest, page=page) # category = Category.query.get(category_id) # if not category: # abort(404) # category_type = category.type # elif search_term: # # Here we are handling the search for a question not # # case sensitive search if the term is a substring of the question # questions = Question.query.filter( # func.lower(Question.question).contains( # search_term.lower())).paginate( # max_per_page=num_quest, page=page) # category_type = ' ' # else: # questions = Question.query.paginate( # max_per_page=num_quest, page=page) # category_type = ' ' # questions = [dict(question.format()) for question in questions.items] # categories = Category.query.all() # category_result = {} # for category in categories: # category_result[category.id] = category.type # result = { # "questions": questions, # "total_questions": len(questions), # "current_category": category_type, # 'categories': category_result # } # return result @app.route('/questions', methods=['GET']) def get_questions(): video_id = request.args.get('video_id', int) if not video_id: abort(422) result = Question.query.filter(Question.video_id == video_id).order_by( asc(Question.date)).all() result_list = [] for question in result: question = question.format() answer_list = [] for ans in question.pop('answers'): ans = ans.format() answer_list.append(ans) question['answers'] = answer_list result_list.append(question) print(result_list) return jsonify({'data': result_list, 'message': 'success'}) @app.route('/questions/<int:question_id>', methods=['DELETE']) def delete_question(question_id): question = Question.query.get(question_id) if not question: abort(404) try: question.delete() except Exception: abort(500) return jsonify({'message': "Delete Successful"}) def sms_notif(message): from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console # DANGER! This is insecure. See http://twil.io/secure account_sid = 'AC60a17f8d85005353a7012cac4e749ae6' auth_token = 'e4721530aaf8ce3eec025255586bf827' client = Client(account_sid, auth_token) message = client.messages.create(body=message, from_='+12058097816', to='+237679904987') print('successfully sent the message') @app.route('/questions', methods=['POST']) def add_question(): data = request.json if (data.get('question') == '') or (data.get('video_id') == ''): abort(422) video = Video.query.get(data.get('video_id')) message = f"video:{video.name} has question:{data.get('question', '')}" try: date = datetime.now() question = Question(question=data.get('question', ''), date=date, video_id=data.get('video_id')) question.insert() except Exception: abort(422) sms_notif(message) return jsonify({'message': 'success'}) @app.route('/answers', methods=['GET']) def get_answers(): question_id = request.args.get('question_id', int) if not question_id: abort(422) result = Answer.query.order_by(asc(Answer.date)).all() result_list = [] for answer in result: answer = answer.format() result_list.append(answer) return jsonify({'data': result_list, 'message': 'success'}) @app.route('/answers/<int:answer_id>', methods=['DELETE']) def delete_answer(answer_id): answer = Answer.query.get(answer_id) if not answer: abort(404) try: answer.delete() except Exception: abort(500) return jsonify({'message': "Delete Successful"}) @app.route('/answers', methods=['POST']) def add_answer(): data = request.json if (data.get('answer') == '') or (data.get('question_id') == ''): abort(422) # try: date = datetime.now() answer = Answer(answer=data.get('answer', ''), date=date, question_id=data.get('question_id')) answer.insert() # except Exception: # abort(422) return jsonify({'message': 'success'}) @app.route('/number', methods=['GET']) def get_number(): question_id = request.args.get('question_id', int) if not question_id: abort(422) result = Number.query.get().one_or_none() if result: result = result.format() result['message'] = 'success' else: result['message'] = 'fail' return jsonify(result) @app.route('/number/<int:number_id>', methods=['DELETE']) def delete_number(number_id): number = Number.query.get(number_id) if not number: abort(404) try: number.delete() except Exception: abort(500) return jsonify({'message': "Delete Successful"}) @app.route('/number', methods=['POST']) def add_nuber(): data = request.json if (data.get('number') == '') or (data.get('question_id') == ''): abort(422) # try: date = datetime.now() number = Number(number=data.get('number', '')) number.insert() # except Exception: # abort(422) return jsonify({'message': 'success'}) @app.route('/timetable', methods=['POST']) def add_timetable(): data = request.json if (data.get('name') == '') or (data.get('link') == '')\ or (data.get('time') == '') or (data.get('teacher_id') == '')\ or (data.get('start_time') == '') or (data.get('end_time') == '')\ or (data.get('signup_time')) == '': abort(422) date = datetime.strptime(data.get('time'), "%Y-%m-%d %H:%M") signup_time = datetime.strptime(data.get('signup_time'), "%Y-%m-%d %H:%M") name = data.get('name') link = data.get('link') exam_id = data.get('exam_id') teacher_id = data.get('teacher_id') start_time = data.get('start_time') end_time = data.get('end_time') studio = data.get('studio') exam_type_id = data.get('exam_level_id') if data.get( 'exam_level_id') else None # try: timetable = TimeTable(name=name, link=link, time=date, teacher_id=teacher_id, exam_id=exam_id, exam_type_id=exam_type_id, start_time=start_time, end_time=end_time, signup_time=signup_time, studio=studio) timetable.insert() # except Exception: # abort(422) return jsonify({'status': 'success', 'id': timetable.id}) @app.route('/timetable', methods=['GET']) def get_timetable(): params = request.args exam_id = params.get('exam_id', type=int, default=None) exam_type_id = params.get('exam_level_id', type=int, default=None) teacher_id = params.get('teacher_id', type=int, default=None) accepted = params.get('accepted', type=bool, default=None) print(params.get('time', type=str, default=None)) date = datetime.strptime(params.get('time', type=str), timetable_time_format) if params.get( 'time', type=str) else None if teacher_id: teacher = User.query.get(teacher_id) teacher_id = None if teacher.format()['admin'] else teacher_id if teacher_id and exam_id and exam_type_id and accepted: timetable = TimeTable.query.filter( TimeTable.teacher_id == teacher_id, TimeTable.exam_type_id == exam_type_id, TimeTable.accepted == accepted) elif teacher_id and exam_id and accepted and not exam_type_id: timetable = TimeTable.query.filter( TimeTable.teacher_id == teacher_id, TimeTable.exam_id == exam_id, TimeTable.accepted == accepted) elif teacher_id and exam_id and not accepted and not exam_type_id: timetable = TimeTable.query.filter( TimeTable.teacher_id == teacher_id, TimeTable.exam_id == exam_id) elif teacher_id and exam_type_id and not accepted and not exam_id: timetable = TimeTable.query.filter( TimeTable.teacher_id == teacher_id, TimeTable.exam_type_id == exam_type_id) elif accepted and exam_type_id and not teacher_id and not exam_id: timetable = TimeTable.query.filter( TimeTable.accepted == accepted, TimeTable.exam_type_id == exam_type_id) elif accepted and exam_id and not teacher_id and not exam_type_id: timetable = TimeTable.query.filter(TimeTable.accepted == accepted, TimeTable.exam_id == exam_id) elif exam_type_id: timetable = TimeTable.query.filter( TimeTable.exam_type_id == exam_type_id) elif exam_id: timetable = TimeTable.query.filter(TimeTable.exam_id == exam_id) elif teacher_id: timetable = TimeTable.query.filter( TimeTable.teacher_id == teacher_id) else: abort(422) timetable = timetable.filter( TimeTable.time >= date, TimeTable.time <= date + timedelta(hours=23, minutes=59)) result = [] for a_timetable in timetable: ttable = a_timetable.format() # students = [] # for student in ttable.get('students', []): # students.append(student.format()) # ttable['students'] = students result.append(ttable) return jsonify({ 'data': result, 'status': 'success', }) @app.route('/timetable/accept', methods=['PUT']) @requires_auth def accept_timetable(): data = request.json if (data.get('id') == ''): abort(422) timetable = TimeTable.query.filter( TimeTable.id == data.get('id')).first() try: timetable.accepted = True if not timetable.accepted else False timetable.update() except Exception: abort(422) return jsonify({'status': 'success'}) @app.route('/timetable', methods=['PUT']) @requires_auth def update_timetable(): data = request.json if (data.get('id') == ''): abort(422) timetable = TimeTable.query.filter( TimeTable.id == data.get('id')).first() try: timetable.name = data.get('name') if data.get( 'name') else timetable.name timetable.link = data.get('link') if data.get( 'link') else timetable.link timetable.start_time = data.get('start_time') if data.get( 'start_time') else timetable.start_time timetable.end_time = data.get('end_time') if data.get( 'end_time') else timetable.end_time timetable.signup_time = datetime.strptime( data.get('signup_time'), "%Y-%m-%d %H:%M") if data.get( 'signup_time') else timetable.signup_time timetable.studio = data.get('studio') if data.get( 'studio') else timetable.studio timetable.update() except Exception: abort(422) return jsonify({'status': 'success'}) @app.route('/timetable/<int:timetable_id>', methods=['DELETE']) @requires_auth @requires_admin def delete_timetable(timetable_id): timetable = TimeTable.query.get(timetable_id) if not timetable: abort(404) try: timetable.delete() except Exception: abort(500) return jsonify({'message': "Delete Successful"}) @app.route('/student', methods=['GET']) def get_student(): timetable_id = request.args.get('timetable_id', int) if not timetable_id: abort(422) students = Student.query.get().one_or_none() result = [] if students: for student in students: result.append(result.format()) else: return jsonify({'students': result, 'status': 'fail'}) return jsonify({'students': result, 'status': 'pass'}) @app.route('/student/<int:student_id>', methods=['DELETE']) def delete_student(student_id): student = Student.query.get(student_id) if not student: abort(404) try: student.delete() except Exception: abort(500) return jsonify({'message': "Delete Successful"}) @app.route('/student', methods=['POST']) def add_student(): data = request.json print(data) if (data.get('student') == '') or (data.get('timetable_id') == ''): abort(422) student = Student.query.get(data.get('student')) if student: return jsonify({ 'message': 'You are already signedup / Vous êtes déjà inscrit' }) try: student = Student(student=data.get('student'), timetable_id=data.get('timetable_id')) student.insert() except Exception: abort(422) return jsonify({ 'message': "Vous vous êtes inscrit avec succès / You have successfully signed Up" }) # @app.route('/questions/search', methods=['POST']) # def search_question(): # search_term = request.json.get('searchTerm', '') # result = question_get_return(1, search_term=search_term) # if not result.get('questions'): # abort(404) # return jsonify(result) # @app.route("/categories/<int:category_id>/questions", methods=['GET']) # def get_question_per_category(category_id): # result = question_get_return(1, category_id=category_id) # if not result: # abort(404) # return jsonify(result) # @app.route('/quizzes', methods=['POST']) # def quizes(): # data = request.json # previous_questions_list = data.get('previous_questions') # quiz_category = data.get('quiz_category') # if not quiz_category: # abort(422) # question = Question.query.filter( # Question.category == quiz_category.get('id')).filter( # Question.id.notin_(previous_questions_list)).order_by( # func.random()).limit(1).all() # if question: # question = dict(question[0].format()) # return jsonify({'question': question}) @app.errorhandler(404) def not_found(error): if request.path.startswith("/api/"): return jsonify({'status': 'fail', 'message': 'Not Found'}), 404 return send_from_directory(app.static_folder, 'index.html') @app.errorhandler(422) def unprocessable(error): return jsonify({ 'status': 'fail', 'message': f'Unprocessable {str(error)}' }), 422 @app.errorhandler(400) def bad_request(error): return jsonify({'status': 'fail', 'message': 'Bad Request'}), 400 @app.errorhandler(401) def unauthorized(error): return jsonify({ 'status': 'fail', 'message': 'Your password is not correct.' }), 401 @app.errorhandler(500) def sever_error(error): return jsonify({'status': 'fail', 'message': 'Sever Error'}), 500 return app
def init_app(current_app): global app global bcrypt app = current_app bcrypt = Bcrypt(app)
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask import request from flask_bcrypt import Bcrypt from flask_login import LoginManager import logging app = Flask(__name__,instance_relative_config= True) app.config.from_object('config') #app.config.from_pyfile('config.py') db = SQLAlchemy(app) bcrypt = Bcrypt(app) login_manager = LoginManager(app) login_manager.login_view = "login_page" login_manager.login_message_category = 'info' #logging.basicConfig(filename = "/tmp/log.txt", filemode = "w", level= logging.DEBUG, format= "%(asctime)s - %(levelname)s - %(message)s") from appraisal_report_app import routes
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_mail import Mail from datetime import timedelta app = Flask(__name__) app.config['SECRET_KEY'] = '7749a40aa6e1e5d1b179d879aef51844' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=10) app.config['SESSION_REFRESH_EACH_REQUEST'] = True db = SQLAlchemy(app) bcrypt = Bcrypt(app) login_manager = LoginManager(app) login_manager.login_view = 'login' login_manager.login_message_category = 'info' app.config['MAIL_SERVER'] = 'smtp.seznam.cz' app.config['MAIL_PORT'] = 587 app.config['MAIL_USE_TLS'] = True app.config['MAIL_USERNAME'] = '******' app.config['MAIL_PASSWORD'] = '******' mail = Mail(app) # [email protected] # iisCinemaServer from cinema import routes, errors # @@@@@@@@@@@@@@@@@@ INIT @@@@@@@@@@@@@@@@@@@@@@@@@@@
from flask import Flask from flask_login import LoginManager from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt app = Flask(__name__) app.config['SECRET_KEY'] = "3184cf50b884fd2828b2a084ac04d518f7c4f4e8f22f416a" # app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://*****:*****@localhost/project-2" app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://*****:*****@ec2-54-225-118-55.compute-1.amazonaws.com:5432/d96rrep6atbc84" app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True # added just to suppress a warning UPLOAD_FOLDER = './app/static/uploads' DEFAULT_BIO = 'This person has not entered a bio.' db = SQLAlchemy(app) bcryptHash = Bcrypt(app) # Flask-Login login manager login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' app.config.from_object(__name__) from app import views
from _import import postprocess_move from commands import AddUser, ImportMove, DeleteMove, ListMoves from filters import register_filters, register_globals, radian_to_degree, get_city from login import login_manager, load_user, LoginForm from model import db, Move, Sample, MoveEdit, UserPreference, AlembicVersion try: from urllib.parse import quote_plus except ImportError: from urllib import quote_plus as __quote_plus quote_plus = lambda x: __quote_plus(x.encode('utf-8')) app = Flask('openmoves') fujs = FlaskUtilJs(app) app_bcrypt = Bcrypt() migrate = Migrate(app, db) register_filters(app) register_globals(app) def _parse_revision(filename): pattern = re.compile(r"revision = '(\d+)'") with open(filename, 'r') as f: for line in f: match = pattern.match(line) if match: return int(match.group(1)) raise RuntimeError("Failed to parse revision from %s" % filename)
from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt fl_bcrypt = Bcrypt() db = SQLAlchemy() def connect_db(app): """ Connect to database. """ db.app = app db.init_app(app) class User(db.Model): """ USER. """ __tablename__ = "users" username = db.Column(db.String(20), primary_key=True, nullable=False, unique=True) password = db.Column(db.Text, nullable=False) email = db.Column(db.String(50), nullable=False, unique=True) first_name = db.Column(db.String(30), nullable=False)
def sign_up_save(): ''' This function takes POST http request with a URL of "/signup/save". It firstly reads the user submitted username, password1 and password2. It then connects to the database to check if there is already an existing username in the database. The function also checks whether the user provided all the necessary information; whether the format of the username and password are correct and whether the two passwords match. If any of the above condition failed, the function will return user with "signup_index.html" with error message. If not, the function will insert the user provided information to the database and return "signup_succeed_index.html" page to user indicating the user has successfully created a new account. :return: "signup_index.html" or "signup_succeed_index.html" ''' bcrypt = Bcrypt(webapp) # need to trim the user name username = request.form.get('username', "") password1 = request.form.get('password1', "") password2 = request.form.get('password2', "") # connect to database cnx = get_database() cursor = cnx.cursor() query = "SELECT COUNT(username) FROM user_info WHERE username = %s " cursor.execute(query, (username,)) results = cursor.fetchall() numberOfExistUser = results[0][0] if username == "" or password1 == "" or password2 == "": error_msg = "Error: All fields are required!" return render_template("signup_index.html", title="Sign Up", error_msg=error_msg, username=username, password1=password1, password2=password2) if re.findall(r'\s+', username) != []: error_msg = "Error: No space allowed in user name!" return render_template("signup_index.html", title="Sign Up", error_msg=error_msg, username=username, password1=password1, password2=password2) if numberOfExistUser != 0: error_msg = "Error: User name already exist!" return render_template("signup_index.html", title="Sign Up", error_msg=error_msg, username=username, password1=password1, password2=password2) if not (password1 == password2): error_msg = "Error: Two passwords not matching!" return render_template("signup_index.html", title="Sign Up", error_msg=error_msg, username=username, password1=password1, password2=password2) if (len(username) > 20 or len(username) < 1) or not all(c in validUsernameChar for c in username): print(len(username)) error_msg = "Error: Username violation, username must have length between 1 to 20, only letters and numbers allowed" return render_template("signup_index.html", title="Sign Up", error_msg=error_msg, username=username, password1=password1, password2=password2) if len(password1) > 16 or len(password1) < 1: error_msg = "Error: Password length violation" return render_template("signup_index.html", title="Sign Up", error_msg=error_msg, username=username, password1=password1, password2=password2) ts = time.time() timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') password = bcrypt.generate_password_hash(password1).decode("utf-8") query = ''' INSERT INTO user_info (username,password,create_date,active) VALUES (%s,%s, %s,1) ''' cursor.execute(query, (username, password, timestamp)) cnx.commit() # Add error catch here for sql return render_template("signup_succeed_index.html", title="Sign Up Succeed", username=username, password=password1)
def create(db): from interNect.models import User, Post, Pending, Company from flask_bcrypt import Bcrypt db.create_all() bcrypt = Bcrypt() password = bcrypt.generate_password_hash('1234').decode('utf-8') user = User(username='******', email='*****@*****.**', password=password, lname="Aman", fname="aman", gender='male') u = User(username='******', email='*****@*****.**', password=password, lname="Aman", fname="aman", gender='male') c = Company(company_name="Google", email="*****@*****.**", password=password) company = Company(company_name="Microsoft", email="*****@*****.**", password=password) db.session.add(user) db.session.add(u) db.session.add(c) db.session.add(company) db.session.commit() post = Post( title="IT intern", content= "Our Software Engineering company known for innovative technology seeks a self-directed IT intern with a passion for technology, collaboration, and creative problem-solving. The intern will actively contribute to meaningful projects and work closely with a mentor and with senior leadership.", company_id=1) post2 = Post( title="Software Engineering Intern", content= "Our Company seeks an intern with experience in software design, coding and debugging. The intern will gain exciting real-world software engineering experience at a thriving company. We frequently work in small teams to solve problems, explore new technologies, and learn from one another. The ideal intern for this environment will be enthusiastic and collaborative.", company_id=2) post3 = Post( title="Manufacturing Intern Job", content= "Our Company, an intense and exciting company, is looking for interns to join our creative team of engineers working to develop systems and analysis for a wide variety of companies and industries. Our engineers are hard-working, smart, goal-oriented and creative, and they are looking for interns to train to participate in every level of system design and orientation. The interns hired for this position should expect to learn all facets of manufacturing, and will leave this position with invaluable skills and industry knowledge. Also, this internship program is highly regarded in our field, so successful participation will be a great addition to your resume.", company_id=2) post4 = Post( title="Graphic Design Intern", content= "Are you a student interested in building real-world graphic design experience with an award-winning team? We’re a forward-thinking advertising agency looking for a talented and knowledgeable designer with fresh, creative ideas and an excellent eye for detail. Come work for one of the area’s leading advertising agencies and learn from some of the best in the business.", company_id=2) post5 = Post( title="HR (Human Resources) Intern", content= "Fast-growing marketing agency seeks a personable and highly motivated HR intern to support the HR manager in day-to-day administrative tasks and activities. If you’re ready to kickstart your career in Human Resources and build real-world experience with recruiting, payroll, employee development, and the coordination of HR policies and procedures, this is the internship for you.", company_id=2) db.session.add(post) db.session.add(post2) db.session.add(post3) db.session.add(post4) db.session.add(post5) db.session.commit() print("\n") print(Post.query.all())
from flask import Flask from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_sqlalchemy import SQLAlchemy from flask_wtf.csrf import CSRFProtect from flask_mail import Mail import logging from mast.config import Config import os db = SQLAlchemy() bcr = Bcrypt() csrf = CSRFProtect() mail = Mail() login_manager = LoginManager() login_manager.login_view = 'users.login' login_manager.login_message_category = 'info' logging.basicConfig( format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S') def create_app(configuration=Config): app = Flask(__name__) app.config.from_object(configuration) try: if not os.path.exists(app.config['LANDING_DIR']):
def create_app(): """Set up the application.""" flask_app = Flask(__name__.split('.')[0]) local = CONFIG_BROKER['local'] flask_app.config.from_object(__name__) flask_app.config['LOCAL'] = local flask_app.debug = CONFIG_SERVICES['debug'] flask_app.config['SYSTEM_EMAIL'] = CONFIG_BROKER['reply_to_email'] # Future: Override config w/ environment variable, if set flask_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.is_local = local if SesEmail.is_local: 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) JsonResponse.debugMode = flask_app.debug if CONFIG_SERVICES['cross_origin_url'] == "*": CORS(flask_app, supports_credentials=False, allow_headers="*", expose_headers="X-Session-Id") else: CORS(flask_app, supports_credentials=False, origins=CONFIG_SERVICES['cross_origin_url'], allow_headers="*", expose_headers="X-Session-Id") # Enable DB session table handling flask_app.session_interface = UserSessionInterface() # Set up bcrypt bcrypt = Bcrypt(flask_app) @flask_app.teardown_appcontext def teardown_appcontext(exception): GlobalDB.close() @flask_app.before_request def before_request(): # Set global value for local g.is_local = local sess = GlobalDB.db().session # setup user g.user = None if session.get('name') is not None: g.user = sess.query(User).filter_by(user_id=session['name']).one_or_none() # Root will point to index.html @flask_app.route("/", methods=["GET"]) def root(): return "Broker is running" @flask_app.errorhandler(ResponseException) def handle_response_exception(exception): return JsonResponse.error(exception, exception.status) @flask_app.errorhandler(Exception) def handle_exception(exception): wrapped = ResponseException(str(exception), StatusCode.INTERNAL_ERROR, type(exception)) return JsonResponse.error(wrapped, wrapped.status) # Add routes for modules here add_login_routes(flask_app, bcrypt) add_file_routes(flask_app, CONFIG_BROKER['aws_create_temp_credentials'], local, broker_file_path) add_user_routes(flask_app, flask_app.config['SYSTEM_EMAIL'], bcrypt) add_domain_routes(flask_app) add_exception_handlers(flask_app) return flask_app
def hash_pass(passwd): hashed_passwd = Bcrypt().generate_password_hash(passwd).decode('utf-8') return hashed_passwd
from app.common.database import Database # Redis import redis from rq import Queue # Grabs the folder where the script runs. basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SECRET_KEY'] = 'GEOE4947tvfi939gf3v9e' app.config.from_object('app.configuration.Config') app.config['UPLOAD_FOLDER'] = '/home/novutree/novutree_ui/app/static/uploads/' db = SQLAlchemy(app) # flask-sqlalchemy bc = Bcrypt(app) # flask-bcrypt lm = LoginManager() # flask-loginmanager lm.init_app(app) # init the login manager r = redis.Redis() q = Queue(connection=r, default_timeout=36000) # Setup database @app.before_first_request def initialize_database(): Database.initialize() # Import routing, models and Start the App
'my_debug_salt') app.config['TOKEN_EXPIRATION'] = int(os.environ.get('TOKEN_EXPIRATION', 7200)) app.config['CDN_DOMAIN'] = os.environ.get('CLOUDFRONT_DOMAIN') app.config['CDN_DEBUG'] = app.debug app.config['CDN_HTTPS'] = True app.config['TEMPLATES_AUTO_RELOAD'] = True app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False app.config['BABEL_DEFAULT_LOCALE'] = 'fr' app.jinja_env.add_extension('jinja2_time.TimeExtension') # Login Manager login_manager = LoginManager() login_manager.init_app(app) # Bcrypt bcrypt = Bcrypt() bcrypt.init_app(app) # QRCode qrcode = QRcode() qrcode.init_app(app) # Babel domain = Domain(dirname='translations') babel = Babel(default_domain=domain) babel.init_app(app) # Toolbar toolbar = DebugToolbarExtension() toolbar.init_app(app)
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_mail import Mail from .config import Config bcrypt = Bcrypt() db = SQLAlchemy() login_manager = LoginManager() login_manager.login_view = 'users.login' login_manager.login_message_category = 'info' mail = Mail() def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) bcrypt.init_app(app) db.init_app(app) login_manager.init_app(app) mail.init_app(app) from flaskblog.users.routes import users from flaskblog.posts.routes import posts from flaskblog.main.routes import main from flaskblog.errors.handlers import errors
from flask_blog.models import Users, Post from flask import render_template, url_for, redirect, flash, request, abort from flask_bcrypt import Bcrypt from flask_blog.forms import (Registration_form, Log_in_form, Update_acc_form, Post_form, RequestResetForm, ResetPasswordForm) from flask_blog import app, db, mail from flask_login import login_user, current_user, logout_user import os import secrets from flask_mail import Message title = 'ABOUT' bcrypt = Bcrypt(app) #For encryption of password... @app.route("/") @app.route("/home", endpoint='home') def home(): return render_template('home.html') @app.route("/about", endpoint='about') def about(): if current_user.is_authenticated: posts = Post.query.all() return render_template('about.html', posts=posts, title= title) else: flash(f'Not logged in!', 'info') return redirect(url_for('Register')) @app.route("/login", methods=['GET', 'POST'])
from flask_login import LoginManager, UserMixin, login_required, login_user, logout_user, current_user from flask_bcrypt import Bcrypt from flask_cors import CORS, cross_origin import sqlite3, functools, random, string, datetime app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' DATABASE = 'tasks.db' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+DATABASE app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) login_manager = LoginManager() login_manager.init_app(app) socketio = SocketIO(app) bcrypt = Bcrypt(app) CORS(app,supports_credentials=True) class User(db.Model): __tablename__ = 'user' username = db.Column(db.String, primary_key=True) password = db.Column(db.String) authenticated = db.Column(db.Boolean, default=False) def is_active(self): """True, as all users are active.""" return True def get_id(self):
def edit(self): bcrypt = Bcrypt(None) password_hash = bcrypt.generate_password_hash(self.password) self.password = password_hash user_writer.edit_main_info(self)
from flask import Flask, request, render_template from mysqlconnection import MySQLConnector # imports the Bcrypt module # from flask.ext.bcrypt import Bcrypt from flask_bcrypt import Bcrypt app = Flask(__name__) bcrypt = Bcrypt(app) password = '******' pw_hash = bcrypt.generate_password_hash(password) print pw_hash 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 }
def password_exist(self, password): bcrypt = Bcrypt(None) user = user_reader.get_by_id(self._id) return bcrypt.check_password_hash(user.password, password)
def __init__(self, app, usersCollection): self.usersCollection = usersCollection self.bcrypt = Bcrypt(app) app.config['SECRET_KEY'] = SECRET app.config['JWT_AUTH_USERNAME_KEY'] = 'email' app.config['JWT_EXPIRATION_DELTA'] = timedelta(seconds=7*24*60*60) # 7 days
# noinspection PyUnusedLocal def generate_session_key(length): return ''.join([ random.choice( 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') for i in range(length) ]) auth = LoginManager() auth.login_view = "home.index.login" auth.session_protection = "strong" auth_hasher = Bcrypt() @auth.user_loader def load_user(session_token): return User.query.filter_by(token=session_token).first() def do_login(username, password): user = User.query.filter_by(username=username).first() if user is None: return False if not auth_hasher.check_password_hash(user.passhash, password): return False
def setUp(self): app = flask.Flask(__name__) app.config['BCRYPT_LOG_ROUNDS'] = 6 app.config['BCRYPT_HASH_IDENT'] = '2b' self.bcrypt = Bcrypt(app)
config = configparser.ConfigParser() config.read('config.ini') class JSONEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, ObjectId): return str(o) if isinstance(o, datetime.datetime): return str(o) return json.JSONEncoder.default(self, o) app = Flask(__name__) app.config[ 'MONGO_URI'] = config['MONGODB']['URI'] + config['MONGODB']['DATABASE'] app.config['JWT_SECRET_KEY'] = config['JWT']['SECRET'] app.config['JWT_ACCESS_TOKEN_EXPIRES'] = datetime.timedelta(days=1) mongo = PyMongo(app) flask_bcrypt = Bcrypt(app) jwt = JWTManager(app) app.json_encoder = JSONEncoder CORS(app) # noinspection PyPep8 from app.controllers import *
from .model import db, Member, Code, CodeRedeem, QuizQuestion, QuizAnswer from .views import frontend app = Flask(__name__) app.config['SECRET_KEY'] = 'ak3lfka39kalgk3992ksflsj4929rkgslo39502k' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///leaderboard.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['ADMIN_CREDENTIALS'] = ('admin', 'foobar-metasploit-spo-1337') login_manager = LoginManager() login_manager.init_app(app) db.init_app(app) bcrypt = Bcrypt() bcrypt.init_app(app) class ModelViewProtected(ModelView): def is_accessible(self): auth = request.authorization or request.environ.get('REMOTE_USER') if not auth or (auth.username, auth.password) != app.config['ADMIN_CREDENTIALS']: raise HTTPException('', Response( "Please log in.", 401, {'WWW-Authenticate': 'Basic realm="Login Required"'} )) return True admin = Admin(app, name='leaderboard', template_mode='bootstrap3') admin.add_view(ModelViewProtected(Member, db.session)) admin.add_view(ModelViewProtected(Code, db.session))
from flask_bcrypt import Bcrypt from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() #database initialization bcrypt = Bcrypt() #for encryption
from flask import Flask, render_template, request, redirect, session, flash from flask_bcrypt import Bcrypt from datetime import datetime import re from mysqlconnection import connectToMySQL app = Flask(__name__) app.secret_key = "Welcome to the thunder dome" bcrpyt = Bcrypt(app) EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') @app.route('/') def index(): return render_template('index.html') @app.route('/create_user', methods=['POST']) def create_user(): is_valid = True SpecialSym = ['$', '@', '#', '%'] if len(request.form['fname']) < 2: is_valid = False flash("Please enter a first name") if len(request.form['lname']) < 2: is_valid = False flash("Please enter a last name") if not EMAIL_REGEX.match(request.form['email']):
from flask import Flask #importing Flask class from flask package to use flask function and class from flask_sqlalchemy import SQLAlchemy #importing SQLAlchemy to manage our database from flask_bcrypt import Bcrypt from flask_login import LoginManager app = Flask(__name__) #instanciating imported flask class app.config[ 'SECRET_KEY'] = '51790f49aa35845942c29ff82df9f8c8' #Secret key to secure our app like modifying cookies etc app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' # specify the relative route of the database db = SQLAlchemy(app) #Creating SQLAlchemy instance bcrypt = Bcrypt(app) #Creating Bcrypt instance to manage hashing password login_manager = LoginManager(app) # to manage user's session login_manager.login_view = 'login' #allow us to force the user to login before access to different pages login_manager.login_message_category = 'info' #change the apparence of different info message from webapp import routes
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_mail import Mail from flaskblog.config import Config db = SQLAlchemy() bcrypt = Bcrypt() #instance of object for pw encryption login_manager = LoginManager() login_manager.login_view = 'login' login_manager.login_message_category = 'info' mail = Mail() def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(Config) db.init_app(app) bcrypt.init_app(app) mail.init_app(app) login_manager.init_app(app) from flaskblog.users.routes import users from flaskblog.posts.routes import posts from flaskblog.main.routes import main from flaskblog.errors.handlers import errors app.register_blueprint(posts) app.register_blueprint(users)
from flask_login import LoginManager, current_user, login_user, login_required from wtforms import Form, BooleanField, StringField, PasswordField, validators, TextAreaField, IntegerField, HiddenField from flask_wtf import CSRFProtect import subprocess from datetime import * from flask_user import roles_required, UserManager from flask_sqlalchemy import SQLAlchemy from flask_login import UserMixin app = Flask(__name__) login_manager = LoginManager() login_manager.init_app(app) app.secret_key = '1234567891234567893242341230498120348719035192038471902873491283510981834712039847124123940812903752903847129038471290835710289675413864310867135' csrf = CSRFProtect() csrf.init_app(app) bcrypt = Bcrypt(app) # Define SQLite3 DB app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) # Define the SQLite Tables class userTable(db.Model, UserMixin): user_id = db.Column(db.Integer(), unique=True, nullable=False, primary_key=True) username = db.Column(db.String(20), unique=True, nullable=False) password = db.Column(db.String(60), nullable=False)
from flask_bootstrap import Bootstrap from flask_login import LoginManager from flask_mail import Mail from flask_bcrypt import Bcrypt from flask_cors import CORS from flask import Flask, render_template import pymongo as pm from app.config import Config client = pm.MongoClient( 'mongodb+srv://alan:[email protected]/test') db = client.main bootstrap = Bootstrap() login_manager = LoginManager() secure = Bcrypt() mail = Mail() cors = CORS() def create_app(): app = Flask(__name__, template_folder="templates", static_folder="static") app.config.from_object(Config) secure.init_app(app) mail.init_app(app) login_manager.init_app(app) login_manager.login_view = 'guide.login' bootstrap.init_app(app) cors.init_app(app, supports_credentials=True) app.jinja_env.globals.update(__builtins__)
from flask_bcrypt import Bcrypt bcrypt = Bcrypt() password = '******' hashed_password = bcrypt.generate_password_hash(password=password) print(hashed_password) check = bcrypt.check_password_hash(hashed_password,'wrongpassword') check1 = bcrypt.check_password_hash(hashed_password,'supersecretpassword') print(check) print(check1) from werkzeug.security import generate_password_hash,check_password_hash hashed_pass = generate_password_hash('mypassword') print(hashed_pass) check2 = check_password_hash(hashed_pass,'wrong') check3 = check_password_hash(hashed_pass,'mypassword') print(check2) print(check3)
class BasicTestCase(unittest.TestCase): def setUp(self): app = flask.Flask(__name__) app.config['BCRYPT_LOG_ROUNDS'] = 6 app.config['BCRYPT_HASH_IDENT'] = '2b' app.config['BCRYPT_HANDLE_LONG_PASSWORDS'] = False self.bcrypt = Bcrypt(app) def test_is_string(self): pw_hash = self.bcrypt.generate_password_hash('secret') if PY3: self.assertTrue(isinstance(pw_hash, bytes)) else: 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, b'\xe2\x98\x83')) def test_rounds_set(self): self.assertEqual(self.bcrypt._log_rounds, 6) def test_unicode_hash(self): password = u'東京' h = generate_password_hash(password).decode('utf-8') self.assertTrue(check_password_hash(h, password)) def test_long_password(self): """Test bcrypt maximum password length. The bcrypt algorithm has a maximum password length of 72 bytes, and ignores any bytes beyond that.""" # Create a password with a 72 bytes length password = '******' * 72 pw_hash = self.bcrypt.generate_password_hash(password) # Ensure that a longer password yields the same hash self.assertTrue(self.bcrypt.check_password_hash(pw_hash, 'A' * 80))
from flask import Flask from flask_bcrypt import Bcrypt from flask_cors import CORS from .config import config_by_name from flask_limiter import Limiter from flask_limiter.util import get_remote_address # db = SQLAlchemy() # ma = Marshmallow() flask_bcrypt = Bcrypt() def create_app(config_name): app = Flask(__name__) limiter = Limiter(app, key_func=get_remote_address, default_limits=["100 per minute"]) cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) app.config.from_object(config_by_name[config_name]) # db.init_app(app) # ma.init_app(app) flask_bcrypt.init_app(app) return app
def setUp(self): app = flask.Flask(__name__) app.config['BCRYPT_LOG_ROUNDS'] = 6 app.config['BCRYPT_HASH_IDENT'] = '2b' app.config['BCRYPT_HANDLE_LONG_PASSWORDS'] = True self.bcrypt = Bcrypt(app)
import os from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_debugtoolbar import DebugToolbarExtension from flask_cors import CORS from flask_migrate import Migrate from flask_bcrypt import Bcrypt # new # instantiate the extensions db = SQLAlchemy() toolbar = DebugToolbarExtension() cors = CORS() migrate = Migrate() bcrypt = Bcrypt() # new def create_app(script_info=None): # instantiate the app app = Flask(__name__) # set config app_settings = os.getenv('APP_SETTINGS') app.config.from_object(app_settings) # set up extensions db.init_app(app) toolbar.init_app(app) cors.init_app(app) migrate.init_app(app, db)
def setUp(self): app = flask.Flask(__name__) app.config['BCRYPT_LOG_ROUNDS'] = 6 self.bcrypt = Bcrypt(app)
def upload_file_api(): ''' This function provides users with an api to upload an image together with given username and password. The function will first check if the user info is correct and if it's correct, the function will keep a record of the image and an OpenCV-processed image in the database, with the proper naming scheme. The function can raise exceptions if there are any of the following problems: no file selected; filename too long; wrong extension type; file too large. If the uploaded is valid then we will connect to the database and create a record. First, we assign systematic names to the image and its processed image depending on the user id and their upload counter. Second, we save the image to the cloud, process it through OpenCV and then save the processed image to the cloud. Third, we gather all information and update our file name table in the database. Last we increase the upload counter by 1 and update it. :return: Json string with status code and information string ''' bcrypt = Bcrypt(webapp) try: username = request.form['username'] password = request.form['password'] if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: return http_response(404, "No file upload in the request!") try: file = request.files['file'] except RequestEntityTooLarge: return http_response( 413, "Image too large, file cannot larger than 5mb") # if user does not select file, browser also # submit an empty part without filename if file.filename == '': return http_response(404, "No file selected!") if len(file.filename) >= 50: return http_response(400, "File name too long") if file and allowed_file(file.filename): #===================================================# #======Till this step the file is good to process===# # ===================================================# #rename the upload img as: userpid_useruploadcounter_imagename.extention userFileName = secure_filename( file.filename) # example: example.jpg # connect to database cnx = get_database() cursor = cnx.cursor() query1 = "SELECT password, uid, upload_counter FROM user_info WHERE username = %s and active = 1" cursor.execute(query1, (username, )) results = cursor.fetchall() if len(results) != 1: return http_response(400, "Invalid username or password") correctPwd = bcrypt.check_password_hash( results[0][0], password) if correctPwd: uid = results[0][1] upload_counter = results[0][2] cloudSaveFilename = str(uid) + "_" + str( upload_counter ) + "_" + userFileName #example: 12_1_example.jpg cloudProcessedFileName = "p_" + cloudSaveFilename userDownloadFileName = "processed_" + userFileName # save uploaded img to cloud drive file.save( os.path.join(webapp.config['UPLOAD_FOLDER'], cloudSaveFilename)) #process the img from cloud drive, it will process the img in (img_path) and save processed img in same path Opencv.imageProcess(UPLOAD_FOLDER, cloudSaveFilename, cloudProcessedFileName) #prepare for values for sql fileName = userFileName processedFileName = "processed_" + userFileName uploadImagePath = UPLOAD_FOLDER + cloudSaveFilename processedImagePath = UPLOAD_FOLDER + cloudProcessedFileName ts = time.time() timeStamp = datetime.datetime.fromtimestamp(ts).strftime( '%Y-%m-%d %H:%M:%S') #update file_name table query2 = "INSERT INTO file_info (uid, file_name, upload_image_path, cloud_image_name, processed_image_path, cloud_processed_image_name, create_time) VALUES (%s, %s, %s, %s, %s , %s, %s)" data = (uid, fileName, uploadImagePath, cloudSaveFilename, processedImagePath, cloudProcessedFileName, timeStamp) cursor.execute(query2, data) cnx.commit() #get the newest user upload counter for database query3 = "SELECT upload_counter FROM user_info WHERE username = %s and active = 1" cursor.execute(query3, (username, )) results = cursor.fetchall() upload_counter = results[0][0] #update user_table query4 = "UPDATE user_info SET upload_counter = %s WHERE uid = %s" cursor.execute(query4, (upload_counter + 1, uid)) cnx.commit() print("==>process succeed") # get the image path for both image_before and image_after return http_response(200, "Image Successfully Processed!") else: return http_response(400, "Invalid username or password") else: return http_response( 400, "Not a Correct File Type!" + str(file and allowed_file(file.filename)) + "|" + file.filename) return http_response(123, "Unsupported method!") except Exception as ex: if '413' in str(ex): return http_response( 413, "Image too large, file cannot larger than 5mb") return http_response(400, str(ex))