# ensure mongo is indexed properly mongo_connection.mongo_create_index("apps", "app_name") mongo_connection.mongo_create_index("device_groups", "device_group") mongo_connection.mongo_create_index("users", "user") mongo_connection.mongo_create_index("user_groups", "user_group") mongo_connection.mongo_create_index("cron_jobs", "cron_job_name") # get current list of apps at startup nebula_apps = mongo_connection.mongo_list_apps() print("got list of all mongo apps") # open waiting connection try: app = Flask(__name__) # basic auth for api basic_auth = HTTPBasicAuth(realm='nebula') token_auth = HTTPTokenAuth('Bearer') multi_auth = MultiAuth(basic_auth, token_auth) print("startup completed - now waiting for connections") except Exception as e: print("Flask connection configuration failure - dropping container") print(e, file=sys.stderr) os._exit(2) # this function checks basic_auth to allow access to authenticated users. @basic_auth.verify_password def verify_password(username, password): # if auth_enabled is set to false then always allow access if auth_enabled is False: return True
import urllib.parse from chameleon import PageTemplateLoader from owslib.crs import axisorder_yx from flask import request, make_response, redirect from flask_httpauth import HTTPBasicAuth from multidict import CIMultiDict from mslib.utils import conditional_decorator from mslib.utils import parse_iso_datetime from mslib.index import app_loader # Flask basic auth's documentation # https://flask-basicauth.readthedocs.io/en/latest/#flask.ext.basicauth.BasicAuth.check_credentials app = app_loader(__name__) auth = HTTPBasicAuth() realm = 'Mission Support Web Map Service' app.config['realm'] = realm try: import mss_wms_settings except ImportError as ex: logging.warning( "Couldn't import mss_wms_settings (ImportError:'%s'), creating dummy config.", ex) class mss_wms_settings(object): base_dir = os.path.abspath(os.path.dirname(__file__)) xml_template_location = os.path.join(base_dir, "xml_templates") service_name = "OGC:WMS"
import app import os from app import db from flask import jsonify, request, g, current_app from app.models import User, Event, Admin from app.Face import Facepp from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from flask_restful import Api, Resource, reqparse from werkzeug.datastructures import FileStorage from config import basedir import hashlib from werkzeug.utils import secure_filename from cryptography.fernet import Fernet base_auth = HTTPBasicAuth() token_auth = HTTPTokenAuth(scheme='Token') API = Api(api) imgSecret_key = b'L5udwIEY2jzFimjtANkrHdsdr-_K75yeTidMRc5dYeE=' #加密文件名用的key key = "Dw-h4codShmYMjo9jo6VWrQcYwJlVjdG" secret = "3GmEoY08YFH2QRZbwJoq2WBPMf96JEK6" @api.route('/test', methods=['GET']) @base_auth.login_required def test(): return jsonify(status='fail') @base_auth.verify_password
from flask import g, request, render_template, jsonify, abort from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth from werkzeug.security import generate_password_hash, check_password_hash from itsdangerous import TimedJSONWebSignatureSerializer as JWT from clappets import app, mongodb from clappets.utils import json_response jwt = JWT(app.config['SECRET_KEY'], expires_in=360000) auth = HTTPBasicAuth() auth_relaxed = HTTPBasicAuth() auth_admin = HTTPBasicAuth() users = { "admin" : generate_password_hash("admin"), "sraheja" : generate_password_hash("sraheja"), } @app.route('/auth/', methods=['POST']) def getAuthToken(): req = request.get_json() username = req["username"] password = req["password"] auth_response = {} users = mongodb['users'] user = users.find_one({"_id": username}) if (user == None): auth_response["message"] = "Invalid User Credentials" return json_response(auth_response), 401 else: authenticated = check_password_hash(user['password_hash'], password)
from flask import Blueprint from flask_restful import Resource, Api, reqparse, inputs from flask_httpauth import HTTPBasicAuth from src import utils, msg api_blueprint = Blueprint(__name__, 'api') api = Api(api_blueprint) auth = HTTPBasicAuth() auth.verify_password(utils.verify_password) def send_response(result): return { "id": result.id, "from": result.originator, "to": "+" + str(result.recipients['items'][0].recipient), "message": result.body, "status": result.recipients['items'][0].status, } @api.resource("/message/send") class SendMessage(Resource): @auth.login_required @staticmethod def post(self): parser = reqparse.RequestParser() parser.add_argument("from", required=True, type=str) parser.add_argument("to", required=True, type=str) parser.add_argument("message", required=True, type=str)
logging.basicConfig(level=logging.DEBUG) if len(sys.argv) > 1: assert sys.argv[1:] == ['--debug'] logging.getLogger('zeroconf').setLevel(logging.DEBUG) zeroconf = Zeroconf() print("\nBrowsing services, press Ctrl-C to exit...\n") browser = ServiceBrowser(zeroconf, "_http._tcp.local.", handlers=[on_service_state_change]) app = Flask(__name__) #start flask server canvasURL = 'https://canvas.vt.edu/api/v1/groups/52695/files' foldersURL = 'https://canvas.vt.edu/api/v1/groups/52695/folders' auth = HTTPBasicAuth() #used to do the http authenication client = MongoClient() #getting the mongo database db = client["database"] accounts = db["users"] accountInfo = list(accounts.find()) #convert into list accounts = {} for x in range(0, len(accountInfo)): accounts[accountInfo[x]["username"]] = accountInfo[x][ "password"] #the get_pw was confusing if i kept it as the list above, so i changed it @auth.get_password #check for username in the database
from zapv2 import ZAPv2 import os import requests import json from requests.exceptions import ProxyError torm_api = "etm:8091" #TORM API URL in production mode #torm_api="localhost:37000" #TORM API URL in dev mode tormurl = "http://" + torm_api + "/" #TORM API full URL target = '0.0.0.0' #indicates in which IP address the API listens to por = 80 #indicates the port api_version = 'r4' #represents the current version of the API zap = ZAPv2( ) #call to the OWAZP ZAP python API library (https://github.com/zaproxy/zaproxy/wiki/ApiPython) app = Flask(__name__, static_url_path="") auth = HTTPBasicAuth() #for securing api calls using HTTP basic authentication ess_called = 0 ess_finished = 0 scans = [] #setting empty secjobs list when api starts sites_to_be_scanned = [] #To be used while implementing HTTPBasicAuth @auth.get_password def get_password(username): if username == 'miguel': return 'python' return None #To be used while implementing HTTPBasicAuth
def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs) capp.Task = ContextTask return capp capp = setup_celery() from .models import User, Role user_datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(app, user_datastore) # will be replaced by a MultiAuth using tokens later apiauth = HTTPBasicAuth(realm=app.name) @apiauth.verify_password def verify_password(username, password): g.user = None try: user = (User.query .filter_by(email=username) .one()) if fs_verify_password(password, user.password): g.user = user return True except:
def create_server(test_config=None): # Scoreboard Object and Data Store # scoreboard = Scoreboard("SEOULAI") # Basic Authentication auth = HTTPBasicAuth() @auth.get_password def get_password(username): if username == 'seoulAI': return 'agent' return None @auth.error_handler def unauthorized(): return make_response(jsonify({'error': 'Unauthorized access'}), 401) # create and configure the app app = Flask(__name__, instance_relative_config=True) app.static_url_path = '/static' app.config.from_mapping( SECRET_KEY='dev', #DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), ) app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # Now let's create the websocket socketio = SocketIO(app) @app.errorhandler(BAD_REQUEST) def bad_request(error): return make_response(jsonify({'error': 'Bad request'}), BAD_REQUEST) @app.errorhandler(NOT_FOUND) def not_found(error): return make_response(jsonify({'error': 'Not found'}), NOT_FOUND) # Flask Service @app.errorhandler(SERVER_ERROR) def server_error(error): return make_response(jsonify({'error': 'Server error'}), SERVER_ERROR) @app.route('/move', methods=['GET']) def move(): send_move() return jsonify({'response': 'OK'}) @socketio.on('message') def handle_message(message): print('received message: ' + message) @socketio.on('json') def handle_json(json): print('received json: ' + str(json)) def send_move(): # count is use to create some randomness on test moves global count count += 1 if (count == 4): count = 0 socketio.emit('message', moves[count]) return app
from flask import g from flask_httpauth import HTTPBasicAuth from app.models import User from app.api.errors import error_response basic_auth = HTTPBasicAuth() token_auth = HTTPBasicAuth() @basic_auth.verify_password def verify_password(username, password): user = User.qyery.filter_by(username=username).first() if user is None: return False g.current_user = user return user.check_password(password) @basic_auth.error_handler def basic_auth_error(): return error_response(401) @token_auth.verify_token def verify_token(token): g.current_user = User.check_token(token) if token else None return g.current_user is not None @token_auth.error_handler def token_auth_error():
from flask import Blueprint,g,current_app,jsonify from flask_restful import Resource,marshal_with,Api,fields from models import Article from flask_httpauth import HTTPBasicAuth #导入认证类 from itsdangerous import TimedJSONWebSignatureSerializer as Serializer article_bp = Blueprint('article',__name__) api = Api(article_bp) auth = HTTPBasicAuth() #实例化一个认证对象 @auth.verify_password def verify_password(username_or_token,password): #如果传入用户名和密码 然后进行相关的验证 if username_or_token == 'kangbazi' and password == '123456': g.username = username_or_token return True #当你传过来的是一个token s = Serializer(current_app.config['SECRET_KEY'],expires_in=3600) #验证token是否合法 try: data = s.loads(username_or_token) g.username = data.get('username') return True except: return False
def __init__(self, common, is_gui, mode_settings, mode="share"): self.common = common self.common.log("Web", "__init__", f"is_gui={is_gui}, mode={mode}") self.settings = mode_settings # The flask app self.app = Flask( __name__, static_folder=self.common.get_resource_path("static"), static_url_path= f"/static_{self.common.random_string(16)}", # randomize static_url_path to avoid making /static unusable template_folder=self.common.get_resource_path("templates"), ) self.app.secret_key = self.common.random_string(8) self.generate_static_url_path() self.auth = HTTPBasicAuth() self.auth.error_handler(self.error401) # Verbose mode? if self.common.verbose: self.verbose_mode() # Are we running in GUI mode? self.is_gui = is_gui # If the user stops the server while a transfer is in progress, it should # immediately stop the transfer. In order to make it thread-safe, stop_q # is a queue. If anything is in it, then the user stopped the server self.stop_q = queue.Queue() # Are we using receive mode? self.mode = mode if self.mode == "receive": # Use custom WSGI middleware, to modify environ self.app.wsgi_app = ReceiveModeWSGIMiddleware( self.app.wsgi_app, self) # Use a custom Request class to track upload progress self.app.request_class = ReceiveModeRequest # Starting in Flask 0.11, render_template_string autoescapes template variables # by default. To prevent content injection through template variables in # earlier versions of Flask, we force autoescaping in the Jinja2 template # engine if we detect a Flask version with insecure default behavior. if Version(flask_version) < Version("0.11"): # Monkey-patch in the fix from https://github.com/pallets/flask/commit/99c99c4c16b1327288fd76c44bc8635a1de452bc Flask.select_jinja_autoescape = self._safe_select_jinja_autoescape self.security_headers = [ ("X-Frame-Options", "DENY"), ("X-Xss-Protection", "1; mode=block"), ("X-Content-Type-Options", "nosniff"), ("Referrer-Policy", "no-referrer"), ("Server", "OnionShare"), ] self.q = queue.Queue() self.password = None self.reset_invalid_passwords() self.done = False # shutting down the server only works within the context of flask, so the easiest way to do it is over http self.shutdown_password = self.common.random_string(16) # Keep track if the server is running self.running = False # Define the web app routes self.define_common_routes() # Create the mode web object, which defines its own routes self.share_mode = None self.receive_mode = None self.website_mode = None self.chat_mode = None if self.mode == "share": self.share_mode = ShareModeWeb(self.common, self) elif self.mode == "receive": self.receive_mode = ReceiveModeWeb(self.common, self) elif self.mode == "website": self.website_mode = WebsiteModeWeb(self.common, self) elif self.mode == "chat": self.socketio = SocketIO() self.socketio.init_app(self.app) self.chat_mode = ChatModeWeb(self.common, self) self.cleanup_filenames = []
class Web: """ The Web object is the OnionShare web server, powered by flask """ REQUEST_LOAD = 0 REQUEST_STARTED = 1 REQUEST_PROGRESS = 2 REQUEST_CANCELED = 3 REQUEST_RATE_LIMIT = 4 REQUEST_UPLOAD_INCLUDES_MESSAGE = 5 REQUEST_UPLOAD_FILE_RENAMED = 6 REQUEST_UPLOAD_SET_DIR = 7 REQUEST_UPLOAD_FINISHED = 8 REQUEST_UPLOAD_CANCELED = 9 REQUEST_INDIVIDUAL_FILE_STARTED = 10 REQUEST_INDIVIDUAL_FILE_PROGRESS = 11 REQUEST_INDIVIDUAL_FILE_CANCELED = 12 REQUEST_ERROR_DATA_DIR_CANNOT_CREATE = 13 REQUEST_OTHER = 14 REQUEST_INVALID_PASSWORD = 15 def __init__(self, common, is_gui, mode_settings, mode="share"): self.common = common self.common.log("Web", "__init__", f"is_gui={is_gui}, mode={mode}") self.settings = mode_settings # The flask app self.app = Flask( __name__, static_folder=self.common.get_resource_path("static"), static_url_path= f"/static_{self.common.random_string(16)}", # randomize static_url_path to avoid making /static unusable template_folder=self.common.get_resource_path("templates"), ) self.app.secret_key = self.common.random_string(8) self.generate_static_url_path() self.auth = HTTPBasicAuth() self.auth.error_handler(self.error401) # Verbose mode? if self.common.verbose: self.verbose_mode() # Are we running in GUI mode? self.is_gui = is_gui # If the user stops the server while a transfer is in progress, it should # immediately stop the transfer. In order to make it thread-safe, stop_q # is a queue. If anything is in it, then the user stopped the server self.stop_q = queue.Queue() # Are we using receive mode? self.mode = mode if self.mode == "receive": # Use custom WSGI middleware, to modify environ self.app.wsgi_app = ReceiveModeWSGIMiddleware( self.app.wsgi_app, self) # Use a custom Request class to track upload progress self.app.request_class = ReceiveModeRequest # Starting in Flask 0.11, render_template_string autoescapes template variables # by default. To prevent content injection through template variables in # earlier versions of Flask, we force autoescaping in the Jinja2 template # engine if we detect a Flask version with insecure default behavior. if Version(flask_version) < Version("0.11"): # Monkey-patch in the fix from https://github.com/pallets/flask/commit/99c99c4c16b1327288fd76c44bc8635a1de452bc Flask.select_jinja_autoescape = self._safe_select_jinja_autoescape self.security_headers = [ ("X-Frame-Options", "DENY"), ("X-Xss-Protection", "1; mode=block"), ("X-Content-Type-Options", "nosniff"), ("Referrer-Policy", "no-referrer"), ("Server", "OnionShare"), ] self.q = queue.Queue() self.password = None self.reset_invalid_passwords() self.done = False # shutting down the server only works within the context of flask, so the easiest way to do it is over http self.shutdown_password = self.common.random_string(16) # Keep track if the server is running self.running = False # Define the web app routes self.define_common_routes() # Create the mode web object, which defines its own routes self.share_mode = None self.receive_mode = None self.website_mode = None self.chat_mode = None if self.mode == "share": self.share_mode = ShareModeWeb(self.common, self) elif self.mode == "receive": self.receive_mode = ReceiveModeWeb(self.common, self) elif self.mode == "website": self.website_mode = WebsiteModeWeb(self.common, self) elif self.mode == "chat": self.socketio = SocketIO() self.socketio.init_app(self.app) self.chat_mode = ChatModeWeb(self.common, self) self.cleanup_filenames = [] def get_mode(self): if self.mode == "share": return self.share_mode elif self.mode == "receive": return self.receive_mode elif self.mode == "website": return self.website_mode elif self.mode == "chat": return self.chat_mode else: return None def generate_static_url_path(self): # The static URL path has a 128-bit random number in it to avoid having name # collisions with files that might be getting shared self.static_url_path = f"/static_{self.common.random_string(16)}" self.common.log( "Web", "generate_static_url_path", f"new static_url_path is {self.static_url_path}", ) # Update the flask route to handle the new static URL path self.app.static_url_path = self.static_url_path self.app.add_url_rule( self.static_url_path + "/<path:filename>", endpoint="static", view_func=self.app.send_static_file, ) def define_common_routes(self): """ Common web app routes between all modes. """ @self.auth.get_password def get_pw(username): if username == "onionshare": return self.password else: return None @self.app.before_request def conditional_auth_check(): # Allow static files without basic authentication if request.path.startswith(self.static_url_path + "/"): return None # If public mode is disabled, require authentication if not self.settings.get("general", "public"): @self.auth.login_required def _check_login(): return None return _check_login() @self.app.after_request def add_security_headers(self, r): """ Add security headers to a response """ for header, value in self.security_headers: r.headers.set(header, value) # Set a CSP header unless in website mode and the user has disabled it if not self.settings.get("website", "disable_csp") or self.mode != "website": r.headers.set( "Content-Security-Policy", "default-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'self'; img-src 'self' data:;", ) return r @self.app.errorhandler(404) def not_found(e): mode = self.get_mode() history_id = mode.cur_history_id mode.cur_history_id += 1 return self.error404(history_id) @self.app.errorhandler(405) def method_not_allowed(e): mode = self.get_mode() history_id = mode.cur_history_id mode.cur_history_id += 1 return self.error405(history_id) @self.app.errorhandler(500) def method_not_allowed(e): mode = self.get_mode() history_id = mode.cur_history_id mode.cur_history_id += 1 return self.error500(history_id) @self.app.route("/<password_candidate>/shutdown") def shutdown(password_candidate): """ Stop the flask web server, from the context of an http request. """ if password_candidate == self.shutdown_password: self.force_shutdown() return "" abort(404) if self.mode != "website": @self.app.route("/favicon.ico") def favicon(): return send_file( f"{self.common.get_resource_path('static')}/img/favicon.ico" ) def error401(self): auth = request.authorization if auth: if (auth["username"] == "onionshare" and auth["password"] not in self.invalid_passwords): print(f"Invalid password guess: {auth['password']}") self.add_request(Web.REQUEST_INVALID_PASSWORD, data=auth["password"]) self.invalid_passwords.append(auth["password"]) self.invalid_passwords_count += 1 if self.invalid_passwords_count == 20: self.add_request(Web.REQUEST_RATE_LIMIT) self.force_shutdown() print( "Someone has made too many wrong attempts to guess your password, so OnionShare has stopped the server. Start sharing again and send the recipient a new address to share." ) return render_template("401.html", static_url_path=self.static_url_path), 401 def error403(self): self.add_request(Web.REQUEST_OTHER, request.path) return render_template("403.html", static_url_path=self.static_url_path), 403 def error404(self, history_id): mode = self.get_mode() if mode.supports_file_requests: self.add_request( self.REQUEST_INDIVIDUAL_FILE_STARTED, request.path, { "id": history_id, "status_code": 404 }, ) self.add_request(Web.REQUEST_OTHER, request.path) return render_template("404.html", static_url_path=self.static_url_path), 404 def error405(self, history_id): mode = self.get_mode() if mode.supports_file_requests: self.add_request( self.REQUEST_INDIVIDUAL_FILE_STARTED, request.path, { "id": history_id, "status_code": 405 }, ) self.add_request(Web.REQUEST_OTHER, request.path) return render_template("405.html", static_url_path=self.static_url_path), 405 def error500(self, history_id): mode = self.get_mode() if mode.supports_file_requests: self.add_request( self.REQUEST_INDIVIDUAL_FILE_STARTED, request.path, { "id": history_id, "status_code": 500 }, ) self.add_request(Web.REQUEST_OTHER, request.path) return render_template("500.html", static_url_path=self.static_url_path), 500 def _safe_select_jinja_autoescape(self, filename): if filename is None: return True return filename.endswith((".html", ".htm", ".xml", ".xhtml")) def add_request(self, request_type, path=None, data=None): """ Add a request to the queue, to communicate with the GUI. """ self.q.put({"type": request_type, "path": path, "data": data}) def generate_password(self, saved_password=None): self.common.log("Web", "generate_password", f"saved_password={saved_password}") if saved_password is not None and saved_password != "": self.password = saved_password self.common.log( "Web", "generate_password", f'saved_password sent, so password is: "{self.password}"', ) else: self.password = self.common.build_password() self.common.log("Web", "generate_password", f'built random password: "******"') def verbose_mode(self): """ Turn on verbose mode, which will log flask errors to a file. """ flask_log_filename = os.path.join(self.common.build_data_dir(), "flask.log") log_handler = logging.FileHandler(flask_log_filename) log_handler.setLevel(logging.WARNING) self.app.logger.addHandler(log_handler) def reset_invalid_passwords(self): self.invalid_passwords_count = 0 self.invalid_passwords = [] def force_shutdown(self): """ Stop the flask web server, from the context of the flask app. """ # Shutdown the flask service try: func = request.environ.get("werkzeug.server.shutdown") if func is None and self.mode != "chat": raise RuntimeError("Not running with the Werkzeug Server") func() except Exception: pass self.running = False # If chat, shutdown the socket server if self.mode == "chat": self.socketio.stop() def start(self, port): """ Start the flask web server. """ self.common.log("Web", "start", f"port={port}") # Make sure the stop_q is empty when starting a new server while not self.stop_q.empty(): try: self.stop_q.get(block=False) except queue.Empty: pass # In Whonix, listen on 0.0.0.0 instead of 127.0.0.1 (#220) if os.path.exists("/usr/share/anon-ws-base-files/workstation"): host = "0.0.0.0" else: host = "127.0.0.1" self.running = True if self.mode == "chat": self.socketio.run(self.app, host=host, port=port) else: self.app.run(host=host, port=port, threaded=True) def stop(self, port): """ Stop the flask web server by loading /shutdown. """ self.common.log("Web", "stop", "stopping server") # Let the mode know that the user stopped the server self.stop_q.put(True) # To stop flask, load http://shutdown:[shutdown_password]@127.0.0.1/[shutdown_password]/shutdown # (We're putting the shutdown_password in the path as well to make routing simpler) if self.running: if self.password: requests.get( f"http://127.0.0.1:{port}/{self.shutdown_password}/shutdown", auth=requests.auth.HTTPBasicAuth("onionshare", self.password), ) else: requests.get( f"http://127.0.0.1:{port}/{self.shutdown_password}/shutdown" ) # Reset any password that was in use self.password = None def cleanup(self): """ Shut everything down and clean up temporary files, etc. """ self.common.log("Web", "cleanup") # Cleanup files try: for filename in self.cleanup_filenames: if os.path.isfile(filename): os.remove(filename) elif os.path.isdir(filename): shutil.rmtree(filename) except Exception: # Don't crash if file is still in use pass self.cleanup_filenames = []
def verify_token(user_type: str, user: str, token: str) -> bool: """Verify if the get_token is correct for the given user and return the username if so or raise an error otherwise.""" if 'LOGIN_DISABLED' in app.config and app.config['LOGIN_DISABLED']: return True try: if not db.verify_token(user_type, user, token): return False except ValueError as e: log.warning(str(e)) return False return True client_pw = HTTPBasicAuth() provider_pw = HTTPBasicAuth() @client_pw.verify_password def verify_client_pw(user: str, pw: str) -> bool: """ Verify that the credentials match those in the database. :param user: Username :param pw: Password :return: Authentication result. """ if 'LOGIN_DISABLED' in app.config and app.config['LOGIN_DISABLED']: return True try: return db.verify_password(UserType.CLIENT, user, pw)
from flask_httpauth import HTTPTokenAuth, HTTPBasicAuth from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate # from flask_wtf import CSRFProtect from flask_caching import Cache db = SQLAlchemy() migrate = Migrate() bootstrap = Bootstrap() toolbar = DebugToolbarExtension() auth_token = HTTPTokenAuth() auth_cms = HTTPBasicAuth() auth_pa = HTTPBasicAuth() cache = Cache(config={"CACHE_TYPE": "redis", "CACHE_REDIS_PASSWORD": ""}) # csrf = CSRFProtect() def ext_init(app): db.init_app(app=app) migrate.init_app(app=app, db=db) bootstrap.init_app(app=app) # toolbar.init_app(app=app) cache.init_app(app=app) # csrf.init_app(app=app)
from werkzeug.utils import secure_filename from core.LSH.lsh import SQLDiskLSH from utils import get_matches, _parse_firebase_error, NoFacesFound, MultipleFacesFound from auth.token_system import generate_auth_token, verify_auth_token from auth.firebase_authentication import firebase_auth app = Flask(__name__) CORS(app) app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY") app.config["UPLOAD_FOLDER"] = "./uploads" ALLOWED_EXTENSIONS = set(["png", "jpg", "jpeg"]) http_basic_auth = HTTPBasicAuth() INDEX = SQLDiskLSH() def allowed_file(filename): return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS @app.route("/", methods=["POST"]) @http_basic_auth.login_required def upload_file(): # check if the post request has the file part if "file" not in request.files: resp = jsonify({"message": "No file part in the request"}) resp.status_code = 400
return info @register_versions('return', ['v4']) def _return(self, version, info, project): return {'Info': info} @register_versions('return', ['v5']) def _return_v5(self, version, info, project): return { 'Data': info['FreqModes'], 'Type': 'level2_project_freqmode', 'Count': len(info['FreqModes']) } auth = HTTPBasicAuth() auth.verify_password(lambda _, password: password == SECRET_KEY) class Level2ProjectPublish(MethodView): @auth.login_required def post(self, project): projectsdb = level2db.ProjectsDB() try: projectsdb.publish_project(project) except level2db.ProjectError: abort(http.client.NOT_FOUND) return redirect( url_for('level2viewproject', project=project, version='v5'), code=http.client.CREATED, )
from flask_httpauth import HTTPBasicAuth from flask import g, request from datetime import datetime import pytz from app.ext.database import db # Tables from app.models.tables import User as UserTable # Integration from app.integration.user import User auth_api = HTTPBasicAuth() @auth_api.verify_password def verify_password(username, password): if request.headers.get('token'): _user = UserTable.verify_auth_token(request.headers.get('token')) if _user: g.current_user = UserTable.verify_auth_token( request.headers.get('token')) g.token_used = True # Data e hr do acesso datetimeNow = datetime.now(pytz.timezone("America/Sao_Paulo")) user = User() if user.check_first_seen(g.current_user.id):
from flask_restful import Resource from decorators.ErrorHandler import handle_error from models.Users import Users from flask_httpauth import HTTPBasicAuth from common.Authentication import Authentication auth = HTTPBasicAuth() adminAuth = HTTPBasicAuth() Authentication.init(Authentication, auth, adminAuth) class User(Resource): @handle_error @adminAuth.login_required def get(self): return Users.getAllUsers(self) @handle_error def post(self): return Users.createUser(self) class SingleUser(Resource): @handle_error @auth.login_required def get(self, userID): return Users.getSingleUser(self, userID) @handle_error @adminAuth.login_required def delete(self, userID):
__all__ = ('github_token_auth', 'requires_github_org_membership', 'ltd_login') from functools import wraps from urllib.parse import urljoin from flask import g, current_app from flask_httpauth import HTTPBasicAuth import requests import structlog from apikit import BackendError from .exceptions import GitHubAuthenticationError, GitHubAuthorizationError github_token_auth = HTTPBasicAuth() """GitHub personal access token-based authentication. """ @github_token_auth.verify_password def verify_github_token(username, token): """Verify the GitHub token provided as a password for basic auth. Parameters ---------- username : `str` GitHub username. token : `str` GitHub personal access token (though in principle, a GitHub password could be used, which is not encouraged).
from flask import Flask from flask_httpauth import HTTPBasicAuth from config import Config #Creating and configurating app app = Flask(__name__) app.config.from_object(Config) #Connecting auth authobj = HTTPBasicAuth() #Manage DB from app.db import db @app.before_request def before_request(): db.connect() @app.after_request def after_request(response): db.close() return response # Loading routes from app import routes from app import api
def run(self): logger.info('Starting API Server.') db = database.get_connection(read_only=True, integrity_check=False) app = flask.Flask(__name__) auth = HTTPBasicAuth() @auth.get_password def get_pw(username): if username == config.RPC_USER: return config.RPC_PASSWORD return None ###################### #READ API # Generate dynamically get_{table} methods def generate_get_method(table): def get_method(**kwargs): try: return get_rows(db, table=table, **kwargs) except TypeError as e: #TODO: generalise for all API methods raise APIError(str(e)) return get_method for table in API_TABLES: new_method = generate_get_method(table) new_method.__name__ = 'get_{}'.format(table) dispatcher.add_method(new_method) @dispatcher.add_method def sql(query, bindings=None): if bindings == None: bindings = [] return db_query(db, query, tuple(bindings)) ###################### #WRITE/ACTION API # Generate dynamically create_{transaction} methods def generate_create_method(tx): def split_params(**kwargs): transaction_args = {} common_args = {} private_key_wif = None for key in kwargs: if key in COMMONS_ARGS: common_args[key] = kwargs[key] elif key == 'privkey': private_key_wif = kwargs[key] else: transaction_args[key] = kwargs[key] return transaction_args, common_args, private_key_wif def create_method(**kwargs): try: transaction_args, common_args, private_key_wif = split_params( **kwargs) return compose_transaction(db, name=tx, params=transaction_args, **common_args) except (TypeError, script.AddressError, exceptions.ComposeError, exceptions.TransactionError, exceptions.BalanceError) as error: # TypeError happens when unexpected keyword arguments are passed in error_msg = "Error composing {} transaction via API: {}".format( tx, str(error)) logging.warning(error_msg) raise JSONRPCDispatchException( code=JSON_RPC_ERROR_API_COMPOSE, message=error_msg) return create_method for tx in API_TRANSACTIONS: create_method = generate_create_method(tx) create_method.__name__ = 'create_{}'.format(tx) dispatcher.add_method(create_method) @dispatcher.add_method def get_messages(block_index): if not isinstance(block_index, int): raise APIError("block_index must be an integer.") cursor = db.cursor() cursor.execute( 'select * from messages where block_index = ? order by message_index asc', (block_index, )) messages = cursor.fetchall() cursor.close() return messages @dispatcher.add_method def get_messages_by_index(message_indexes): """Get specific messages from the feed, based on the message_index. @param message_index: A single index, or a list of one or more message indexes to retrieve. """ if not isinstance(message_indexes, list): message_indexes = [ message_indexes, ] for idx in message_indexes: #make sure the data is clean if not isinstance(idx, int): raise APIError( "All items in message_indexes are not integers") cursor = db.cursor() cursor.execute( 'SELECT * FROM messages WHERE message_index IN (%s) ORDER BY message_index ASC' % (','.join([str(x) for x in message_indexes]), )) messages = cursor.fetchall() cursor.close() return messages @dispatcher.add_method def get_supply(asset): if asset == 'BTC': return backend.get_btc_supply(normalize=False) elif asset == 'XCP': return util.xcp_supply(db) else: asset = util.resolve_subasset_longname(db, asset) return util.asset_supply(db, asset) @dispatcher.add_method def get_xcp_supply(): logger.warning("Deprecated method: `get_xcp_supply`") return util.xcp_supply(db) @dispatcher.add_method def get_asset_info(assets): logger.warning("Deprecated method: `get_asset_info`") if not isinstance(assets, list): raise APIError( "assets must be a list of asset names, even if it just contains one entry" ) assetsInfo = [] for asset in assets: asset = util.resolve_subasset_longname(db, asset) # BTC and XCP. if asset in [config.BTC, config.XCP]: if asset == config.BTC: supply = backend.get_btc_supply(normalize=False) else: supply = util.xcp_supply(db) assetsInfo.append({ 'asset': asset, 'asset_longname': None, 'owner': None, 'divisible': True, 'locked': False, 'supply': supply, 'description': '', 'issuer': None }) continue # User‐created asset. cursor = db.cursor() issuances = list( cursor.execute( '''SELECT * FROM issuances WHERE (status = ? AND asset = ?) ORDER BY block_index ASC''', ('valid', asset))) cursor.close() if not issuances: continue #asset not found, most likely else: last_issuance = issuances[-1] locked = False for e in issuances: if e['locked']: locked = True assetsInfo.append({ 'asset': asset, 'asset_longname': last_issuance['asset_longname'], 'owner': last_issuance['issuer'], 'divisible': bool(last_issuance['divisible']), 'locked': locked, 'supply': util.asset_supply(db, asset), 'description': last_issuance['description'], 'issuer': last_issuance['issuer'] }) return assetsInfo @dispatcher.add_method def get_block_info(block_index): assert isinstance(block_index, int) cursor = db.cursor() cursor.execute('''SELECT * FROM blocks WHERE block_index = ?''', (block_index, )) blocks = list(cursor) if len(blocks) == 1: block = blocks[0] elif len(blocks) == 0: raise exceptions.DatabaseError('No blocks found.') else: assert False cursor.close() return block @dispatcher.add_method def fee_per_kb(nblocks=config.ESTIMATE_FEE_NBLOCKS): return backend.fee_per_kb(nblocks) @dispatcher.add_method def get_blocks(block_indexes, min_message_index=None): """fetches block info and messages for the specified block indexes @param min_message_index: Retrieve blocks from the message feed on or after this specific message index (useful since blocks may appear in the message feed more than once, if a reorg occurred). Note that if this parameter is not specified, the messages for the first block will be returned. """ if not isinstance(block_indexes, (list, tuple)): raise APIError("block_indexes must be a list of integers.") if len(block_indexes) >= 250: raise APIError("can only specify up to 250 indexes at a time.") block_indexes_str = ','.join([str(x) for x in block_indexes]) cursor = db.cursor() # The blocks table gets rolled back from undolog, so min_message_index doesn't matter for this query cursor.execute( 'SELECT * FROM blocks WHERE block_index IN (%s) ORDER BY block_index ASC' % (block_indexes_str, )) blocks = cursor.fetchall() cursor.execute( 'SELECT * FROM messages WHERE block_index IN (%s) ORDER BY message_index ASC' % (block_indexes_str, )) messages = collections.deque(cursor.fetchall()) # Discard any messages less than min_message_index if min_message_index: while len(messages) and messages[0][ 'message_index'] < min_message_index: messages.popleft() # Packages messages into their appropriate block in the data structure to be returned for block in blocks: block['_messages'] = [] while len(messages) and messages[0]['block_index'] == block[ 'block_index']: block['_messages'].append(messages.popleft()) #NOTE: if len(messages), then we're only returning the messages for the first set of blocks before the reorg cursor.close() return blocks @dispatcher.add_method def get_running_info(): latestBlockIndex = backend.getblockcount() try: check_database_state(db, latestBlockIndex) except DatabaseError: caught_up = False else: caught_up = True try: cursor = db.cursor() blocks = list( cursor.execute( '''SELECT * FROM blocks WHERE block_index = ?''', (util.CURRENT_BLOCK_INDEX, ))) assert len(blocks) == 1 last_block = blocks[0] cursor.close() except: last_block = None try: last_message = util.last_message(db) except: last_message = None return { 'db_caught_up': caught_up, 'bitcoin_block_count': latestBlockIndex, 'last_block': last_block, 'last_message_index': last_message['message_index'] if last_message else -1, 'running_testnet': config.TESTNET, 'running_testcoin': config.TESTCOIN, 'version_major': config.VERSION_MAJOR, 'version_minor': config.VERSION_MINOR, 'version_revision': config.VERSION_REVISION } @dispatcher.add_method def get_element_counts(): counts = {} cursor = db.cursor() for element in [ 'transactions', 'blocks', 'debits', 'credits', 'balances', 'sends', 'orders', 'order_matches', 'btcpays', 'issuances', 'broadcasts', 'bets', 'bet_matches', 'dividends', 'burns', 'cancels', 'order_expirations', 'bet_expirations', 'order_match_expirations', 'bet_match_expirations', 'messages' ]: cursor.execute("SELECT COUNT(*) AS count FROM %s" % element) count_list = cursor.fetchall() assert len(count_list) == 1 counts[element] = count_list[0]['count'] cursor.close() return counts @dispatcher.add_method def get_asset_names(): cursor = db.cursor() names = [ row['asset'] for row in cursor.execute( "SELECT DISTINCT asset FROM issuances WHERE status = 'valid' ORDER BY asset ASC" ) ] cursor.close() return names @dispatcher.add_method def get_holder_count(asset): asset = util.resolve_subasset_longname(db, asset) holders = util.holders(db, asset) addresses = [] for holder in holders: addresses.append(holder['address']) return {asset: len(set(addresses))} @dispatcher.add_method def get_holders(asset): asset = util.resolve_subasset_longname(db, asset) holders = util.holders(db, asset) return holders @dispatcher.add_method def search_raw_transactions(address, unconfirmed=True): return backend.searchrawtransactions(address, unconfirmed=unconfirmed) @dispatcher.add_method def get_unspent_txouts(address, unconfirmed=False, unspent_tx_hash=None): return backend.get_unspent_txouts(address, unconfirmed=unconfirmed, multisig_inputs=False, unspent_tx_hash=unspent_tx_hash) @dispatcher.add_method def getrawtransaction(tx_hash, verbose=False, skip_missing=False): return backend.getrawtransaction(tx_hash, verbose=verbose, skip_missing=skip_missing) @dispatcher.add_method def getrawtransaction_batch(txhash_list, verbose=False, skip_missing=False): return backend.getrawtransaction_batch(txhash_list, verbose=verbose, skip_missing=skip_missing) @dispatcher.add_method def get_tx_info(tx_hex, block_index=None): # block_index mandatory for transactions before block 335000 source, destination, btc_amount, fee, data = blocks.get_tx_info( tx_hex, block_index=block_index) return source, destination, btc_amount, fee, util.hexlify( data) if data else '' @dispatcher.add_method def unpack(data_hex): data = binascii.unhexlify(data_hex) message_type_id = struct.unpack(config.TXTYPE_FORMAT, data[:4])[0] message = data[4:] # TODO: Enabled only for `send`. if message_type_id == send.ID: unpack_method = send.unpack else: raise APIError('unsupported message type') unpacked = unpack_method(db, message, util.CURRENT_BLOCK_INDEX) return message_type_id, unpacked @dispatcher.add_method # TODO: Rename this method. def search_pubkey(pubkeyhash, provided_pubkeys=None): return backend.pubkeyhash_to_pubkey( pubkeyhash, provided_pubkeys=provided_pubkeys) def _set_cors_headers(response): if not config.RPC_NO_ALLOW_CORS: response.headers['Access-Control-Allow-Origin'] = '*' response.headers[ 'Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS' response.headers[ 'Access-Control-Allow-Headers'] = 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization' @app.route('/', defaults={'args_path': ''}, methods=['GET', 'POST', 'OPTIONS']) @app.route('/<path:args_path>', methods=['GET', 'POST', 'OPTIONS']) # Only require authentication if RPC_PASSWORD is set. @conditional_decorator(auth.login_required, hasattr(config, 'RPC_PASSWORD')) def handle_root(args_path): """Handle all paths, decide where to forward the query.""" if args_path == '' or args_path.startswith('api/') or args_path.startswith('API/') or \ args_path.startswith('rpc/') or args_path.startswith('RPC/'): if flask.request.method == 'POST': # Need to get those here because it might not be available in this aux function. request_json = flask.request.get_data().decode('utf-8') response = handle_rpc_post(request_json) return response elif flask.request.method == 'OPTIONS': response = handle_rpc_options() return response else: error = 'Invalid method.' return flask.Response(error, 405, mimetype='application/json') elif args_path.startswith('rest/') or args_path.startswith( 'REST/'): if flask.request.method == 'GET' or flask.request.method == 'POST': # Pass the URL path without /REST/ part and Flask request object. rest_path = args_path.split('/', 1)[1] response = handle_rest(rest_path, flask.request) return response else: error = 'Invalid method.' return flask.Response(error, 405, mimetype='application/json') else: # Not found return flask.Response(None, 404, mimetype='application/json') ###################### # JSON-RPC API ###################### def handle_rpc_options(): response = flask.Response('', 204) _set_cors_headers(response) return response def handle_rpc_post(request_json): """Handle /API/ POST route. Call relevant get_rows/create_transaction wrapper.""" # Check for valid request format. try: request_data = json.loads(request_json) assert 'id' in request_data and request_data[ 'jsonrpc'] == "2.0" and request_data['method'] # params may be omitted except: obj_error = jsonrpc.exceptions.JSONRPCInvalidRequest( data="Invalid JSON-RPC 2.0 request format") return flask.Response(obj_error.json.encode(), 400, mimetype='application/json') # Only arguments passed as a `dict` are supported. if request_data.get('params', None) and not isinstance( request_data['params'], dict): obj_error = jsonrpc.exceptions.JSONRPCInvalidRequest( data= 'Arguments must be passed as a JSON object (list of unnamed arguments not supported)' ) return flask.Response(obj_error.json.encode(), 400, mimetype='application/json') # Return an error if the API Status Poller checks fail. if not config.FORCE and current_api_status_code: return flask.Response(current_api_status_response_json, 503, mimetype='application/json') # Answer request normally. # NOTE: `UnboundLocalError: local variable 'output' referenced before assignment` means the method doesn’t return anything. jsonrpc_response = jsonrpc.JSONRPCResponseManager.handle( request_json, dispatcher) response = flask.Response(jsonrpc_response.json.encode(), 200, mimetype='application/json') _set_cors_headers(response) return response ###################### # HTTP REST API ###################### def handle_rest(path_args, flask_request): """Handle /REST/ route. Query the database using get_rows or create transaction using compose_transaction.""" url_action = flask_request.path.split('/')[-1] if url_action == 'compose': compose = True elif url_action == 'get': compose = False else: error = 'Invalid action "%s".' % url_action return flask.Response(error, 400, mimetype='application/json') # Get all arguments passed via URL. url_args = path_args.split('/') try: query_type = url_args.pop(0).lower() except IndexError: error = 'No query_type provided.' return flask.Response(error, 400, mimetype='application/json') # Check if message type or table name are valid. if (compose and query_type not in API_TRANSACTIONS) or \ (not compose and query_type not in API_TABLES): error = 'No such query type in supported queries: "%s".' % query_type return flask.Response(error, 400, mimetype='application/json') # Parse the additional arguments. extra_args = flask_request.args.items() query_data = {} if compose: common_args = {} transaction_args = {} for (key, value) in extra_args: # Determine value type. try: value = int(value) except ValueError: try: value = float(value) except ValueError: pass # Split keys into common and transaction-specific arguments. Discard the privkey. if key in COMMONS_ARGS: common_args[key] = value elif key == 'privkey': pass else: transaction_args[key] = value # Must have some additional transaction arguments. if not len(transaction_args): error = 'No transaction arguments provided.' return flask.Response(error, 400, mimetype='application/json') # Compose the transaction. try: query_data = compose_transaction(db, name=query_type, params=transaction_args, **common_args) except (script.AddressError, exceptions.ComposeError, exceptions.TransactionError, exceptions.BalanceError) as error: error_msg = logging.warning( "{} -- error composing {} transaction via API: {}". format(str(error.__class__.__name__), query_type, str(error))) return flask.Response(error_msg, 400, mimetype='application/json') else: # Need to de-generate extra_args to pass it through. query_args = dict([item for item in extra_args]) operator = query_args.pop('op', 'AND') # Put the data into specific dictionary format. data_filter = [{ 'field': key, 'op': '==', 'value': value } for (key, value) in query_args.items()] # Run the query. try: query_data = get_rows(db, table=query_type, filters=data_filter, filterop=operator) except APIError as error: return flask.Response(str(error), 400, mimetype='application/json') # See which encoding to choose from. file_format = flask_request.headers['Accept'] # JSON as default. if file_format == 'application/json' or file_format == '*/*': response_data = json.dumps(query_data) elif file_format == 'application/xml': # Add document root for XML. Note when xmltodict encounters a list, it produces separate tags for every item. # Hence we end up with multiple query_type roots. To combat this we put it in a separate item dict. response_data = serialize_to_xml( {query_type: { 'item': query_data }}) else: error = 'Invalid file format: "%s".' % file_format return flask.Response(error, 400, mimetype='application/json') response = flask.Response(response_data, 200, mimetype=file_format) return response # Init the HTTP Server. init_api_access_log(app) # Run app server (blocking) self.is_ready = True app.run(host=config.RPC_HOST, port=config.RPC_PORT, threaded=True) db.close() return
# coding: utf-8 from flask import g, jsonify from flask_httpauth import HTTPBasicAuth from ..models import User, AnonymousUser from . import api from .errors import unauthorized, forbidden auth = HTTPBasicAuth() # 该认证只用于 API 蓝图, 因此在此初始化 @auth.verify_password def verify_password(email_or_token, password): '''密码验证回调''' if email_or_token == '': # 匿名用户 g.current_user = AnonymousUser() return True if password == '': # 验证token g.current_user = User.verify_auth_token(email_or_token) g.token_used = True # 当前为令牌验证 return g.current_user is not None user = User.query.filter_by(email=email_or_token).first() if not user: return False g.current_user = user # 通过验证的用户保存至全局对象g, 供视图函数访问 g.token_used = False # 当前为密码验证 return user.verify_password(password) # 验证密码 @auth.error_handler def auth_error(): '''自定义错误响应'''
from flask import jsonify, g, current_app from flask_httpauth import HTTPBasicAuth from .models import User auth = HTTPBasicAuth() auth_token = HTTPBasicAuth() @auth.verify_password def verify_password(email, password): g.user = User.query.filter_by(email=email).first() if g.user is None: return False return g.user.verify_password(password) @auth.error_handler def unauthorized(): response = jsonify({'status': 401, 'error': 'unauthorized', 'message': 'please authenticate'}) response.status_code = 401 return response @auth_token.verify_password def verify_auth_token(token, unused): g.user = User.verify_auth_token(token) return g.user is not None @auth_token.error_handler def unauthorized_token(): response = jsonify({'status': 401, 'error': 'unauthorized', 'message': 'please send your authentication token'})
from flask import Flask, jsonify, Blueprint from flask_restful import Api, Resource, reqparse, abort, fields, marshal_with from Users.user_manager import user from flask_httpauth import HTTPBasicAuth user_template = Blueprint("user_template", __name__) ## extends app.py api = Api(user_template) auth = HTTPBasicAuth() ##instance of basic auth USER_DATA = {"Yassa Taiseer": "yassa123"} ## Username&Password for basic auth @auth.verify_password def verify(username, password): if not (username and password): return False return USER_DATA.get(username) == password ## Basic Auth Setup """Users""" ## when user() is used ## user_manager.py is called class mk_user(Resource): @auth.login_required def get(self, Username, Password): boolean = user(Username, Password) status = boolean.add_user()
from sys import argv from random import randrange, shuffle from flask import Flask, render_template, url_for, request from flask_httpauth import HTTPBasicAuth from mafia_params import * app = Flask(__name__) auth = HTTPBasicAuth() auth_GOD = HTTPBasicAuth() preshared_key = "" id = 0 nPlayers = 0 roles = [] ip2role_index_name = {} nComments = 0 comments_ordered = [] @auth.verify_password def verify_password(username, password): if len(username) > 0: return username return None @app.route('/') @auth.login_required def index(): global id, ip2role_index_name username = str(auth.current_user()) role = ""
def create_app(): app = Flask(__name__) CORS(app, resources={r"/v0/calculate": {"origins": "*"}}) auth = HTTPBasicAuth() if path.exists(".env"): from dotenv import load_dotenv load_dotenv() @auth.verify_password def verify_password(username, password): # Auth not required locally, just in production. # Setting an AUTH_OFF flag to any value will turn off auth. auth_off = os.getenv('AUTH_OFF', False) if auth_off: return True # If auth is on, a username and password must be supplied # as environment variables. env_username = os.environ['USERNAME'] env_password = os.environ['PASSWORD'] if (username == env_username) and (password == env_password): return True return False @app.route('/') @auth.login_required def get_root(): return Response( response='welcome', status=300, mimetype='application/json' ) @app.route('/v0/calculate', methods=['POST', 'GET']) @auth.login_required def calculate_from_json(): json_data = request.get_json() args_data = request.args if json_data: raw_input_data = json_data elif args_data: raw_input_data = args_data.to_dict() else: raise ValueError('No input data received.') # Handle invalid input case; return error parsed_input_data = ParseInputData(raw_input_data).parse() if parsed_input_data.valid is False: return Response( response=json.dumps({ 'errors': parsed_input_data.errors, 'status': 'ERROR', }), status=400, mimetype='application/json' ) # Handle valid input case; return data input_data = parsed_input_data.result benefit_estimate = BenefitEstimate(input_data).calculate() use_pretty_print = raw_input_data.get('pretty_print', None) if use_pretty_print: pretty_print_kwargs = {'indent': 4} else: pretty_print_kwargs = {} return Response( response=json.dumps({ **benefit_estimate, 'status': 'OK', }, **pretty_print_kwargs), status=200, mimetype='application/json' ) return app
# third party imports from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_migrate import Migrate from flask_bootstrap import Bootstrap from flask_cors import CORS from flask_httpauth import HTTPBasicAuth from flask_jwt_extended import JWTManager # local imports from config import app_config # db variable initialization db = SQLAlchemy() http_auth = HTTPBasicAuth() login_manager = LoginManager() jwt = JWTManager() migrate = Migrate(compare_type=True) def create_app(config_name): app = Flask(__name__, instance_relative_config=True) app.config.from_object(app_config[config_name]) app.config.from_pyfile('config.py') db.init_app(app) CORS(app) jwt.init_app(app) login_manager.init_app(app) login_manager.login_message = "You must be logged in to access this page"
#### ---- Youtube gen imports: import googleapiclient.discovery from googleapiclient.errors import HttpError import google.oauth2.credentials from youtube_playlist_gen import create_playlist, insert_videos #### ---- Google VAR DEFs: API_SERVICE_NAME = 'youtube' API_VERSION = 'v3' #### ---- APP DEFs: APP = Flask(__name__) AUTH = HTTPBasicAuth() #### ---- API WEBARG DEFs: PLAYLIST_ARGS = { \ 'credentials': fields.Dict(required=True) \ , 'title' : fields.Str(required=True) \ , 'description': fields.Str(required=True) \ } VIDEO_ARGS = { \ 'credentials': fields.Dict(required=True) \ , 'playlist_id' : fields.Str(required=True) \ , 'video_ids': fields.List(fields.Str(required=True)) \ }
def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' basic_auth = HTTPBasicAuth() basic_auth_my_realm = HTTPBasicAuth() basic_auth_my_realm.realm = 'My Realm' basic_custom_auth = HTTPBasicAuth() basic_verify_auth = HTTPBasicAuth() digest_auth = HTTPDigestAuth() digest_auth_my_realm = HTTPDigestAuth() digest_auth_my_realm.realm = 'My Realm' digest_auth_ha1_pw = HTTPDigestAuth(use_ha1_pw = True) @digest_auth_ha1_pw.get_password def get_digest_password(username): if username == 'susan': return get_ha1(username, 'hello', digest_auth_ha1_pw.realm) elif username == 'john': return get_ha1(username, 'bye', digest_auth_ha1_pw.realm) else: return None @basic_auth.get_password def get_basic_password(username): if username == 'john': return 'hello' elif username == 'susan': return 'bye' else: return None @basic_auth_my_realm.get_password def get_basic_password_2(username): if username == 'john': return 'johnhello' elif username == 'susan': return 'susanbye' else: return None @basic_auth_my_realm.hash_password def basic_auth_my_realm_hash_password(username, password): return username + password @basic_auth_my_realm.error_handler def basic_auth_my_realm_error(): return 'custom error' @basic_custom_auth.get_password def get_basic_custom_auth_get_password(username): if username == 'john': return md5('hello').hexdigest() elif username == 'susan': return md5('bye').hexdigest() else: return None @basic_custom_auth.hash_password def basic_custom_auth_hash_password(password): return md5(password).hexdigest() @basic_verify_auth.verify_password def basic_verify_auth_verify_password(username, password): g.anon = False if username == 'john': return password == 'hello' elif username == 'susan': return password == 'bye' elif username == '': g.anon = True return True return False @digest_auth.get_password def get_digest_password(username): if username == 'susan': return 'hello' elif username == 'john': return 'bye' else: return None @digest_auth_my_realm.get_password def get_digest_password_2(username): if username == 'susan': return 'hello' elif username == 'john': return 'bye' else: return None @app.route('/') def index(): return 'index' @app.route('/basic') @basic_auth.login_required def basic_auth_route(): return 'basic_auth:' + basic_auth.username() @app.route('/basic-with-realm') @basic_auth_my_realm.login_required def basic_auth_my_realm_route(): return 'basic_auth_my_realm:' + basic_auth_my_realm.username() @app.route('/basic-custom') @basic_custom_auth.login_required def basic_custom_auth_route(): return 'basic_custom_auth:' + basic_custom_auth.username() @app.route('/basic-verify') @basic_verify_auth.login_required def basic_verify_auth_route(): return 'basic_verify_auth:' + basic_verify_auth.username() + \ ' anon:' + str(g.anon) @app.route('/digest') @digest_auth.login_required def digest_auth_route(): return 'digest_auth:' + digest_auth.username() @app.route('/digest_ha1_pw') @digest_auth_ha1_pw.login_required def digest_auth_ha1_pw_route(): return 'digest_auth:' + digest_auth.username() @app.route('/digest-with-realm') @digest_auth_my_realm.login_required def digest_auth_my_realm_route(): return 'digest_auth_my_realm:' + digest_auth_my_realm.username() self.app = app self.basic_auth = basic_auth self.basic_auth_my_realm = basic_auth_my_realm self.basic_custom_auth = basic_custom_auth self.basic_verify_auth = basic_verify_auth self.digest_auth = digest_auth self.client = app.test_client()
def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' roles_auth = HTTPBasicAuth() @roles_auth.verify_password def roles_auth_verify_password(username, password): g.anon = False if username == 'john': return password == 'hello' elif username == 'susan': return password == 'bye' elif username == 'cindy': return password == 'byebye' elif username == '': g.anon = True return True return False @roles_auth.get_user_roles def get_user_roles(auth): username = auth.username if username == 'john': return 'normal' elif username == 'susan': return ('normal', 'special') elif username == 'cindy': return None @roles_auth.error_handler def error_handler(): return 'error', 403 # use a custom error status @app.route('/') def index(): return 'index' @app.route('/normal') @roles_auth.login_required(role='normal') def roles_auth_route_normal(): return 'normal:' + roles_auth.username() @app.route('/special') @roles_auth.login_required(role='special') def roles_auth_route_special(): return 'special:' + roles_auth.username() @app.route('/normal-or-special') @roles_auth.login_required(role=('normal', 'special')) def roles_auth_route_normal_or_special(): return 'normal_or_special:' + roles_auth.username() @app.route('/normal-and-special') @roles_auth.login_required(role=(('normal', 'special'), )) def roles_auth_route_normal_and_special(): return 'normal_and_special:' + roles_auth.username() self.app = app self.roles_auth = roles_auth self.client = app.test_client()