def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' digest_auth_my_realm = HTTPDigestAuth(realm='My Realm') @digest_auth_my_realm.get_password def get_digest_password_3(username): if username == 'susan': return 'hello' elif username == 'john': return 'bye' else: return None @app.route('/') def index(): return 'index' @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.client = app.test_client()
def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' 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 @app.route('/') def index(): return 'index' @app.route('/digest_ha1_pw') @digest_auth_ha1_pw.login_required def digest_auth_ha1_pw_route(): return 'digest_auth_ha1_pw:' + digest_auth_ha1_pw.username() self.app = app self.client = app.test_client()
def test_unknown_auth_security_scheme(app): from flask_httpauth import HTTPDigestAuth auth = HTTPDigestAuth() @app.get('/') @auth_required(auth) def foo(): pass with pytest.raises(RuntimeError): app.spec
def setup_authentication(app, get_pw_callback): """ This sets up HTTPDigestAuth login to a flask app before each request. :param app: The flask app to add HTTPDigestAuth to. :param get_pw_callback: A function that takes a username and returns cleartext password. :return: Nothing """ auth = HTTPDigestAuth() @auth.login_required def _assert_auth_before_request(): """ Run before each request, relies on the fact that the decorator function @auth.login_required will not run this code if it fails, and if it did not stop just pass thru call by returning None """ app.logger.info(f'User: {auth.username()}') return None app.logger.info(f'Setting up {app} to require login...') auth.get_password(get_pw_callback) app.before_request(_assert_auth_before_request)
class Hello(Resource): auth = HTTPDigestAuth() @auth.get_password def get_pw(username): if username in users: return users.get(username) @auth.login_required def get(self): args = query_post_args.parse_args() input_text = args['text'] return input_text @auth.login_required def post(self): args = query_post_args.parse_args() input_text = args['text'] input_text = input_text.replace('怪我', 'けが').replace( '痺れ', 'しびれ').replace('腫れ物', 'はれもの').replace('火傷', 'やけど') check = 0 for label_name in condition_dict: if label_name == input_text: if '熱' in input_text and bool(re.search(r'\d', input_text)): break condition_text = condition_dict[label_name][1] question = [] for each in condition_text: each = each.split('->') if each[0] not in input_text: question.append([each[0], each[1]]) else: check = 1 if check != 1: okewatashi = input_text return question, output_dict = edit(args['text']) return output_dict
def __init__(self, name, site_data): redis_handle_pw = redis.StrictRedis(site_data["host"], site_data["port"], db=site_data["redis_password_db"], decode_responses=True) self.site_data = site_data startup_dict = redis_handle_pw.hgetall("web") self.qs = Query_Support(site_data) self.file_server_library = Construct_RPC_Library( self.qs, self.site_data) self.app = Flask(name) self.auth = HTTPDigestAuth() self.url_rule_class = URL_Rule_Class(self.app, self.auth) self.auth.get_password(self.get_pw) self.startup_dict = startup_dict self.app.template_folder = 'flask_templates' self.app.static_folder = 'static' self.app.config['SECRET_KEY'] = startup_dict["SECRET_KEY"] self.users = json.loads(startup_dict["users"]) Load_Static_Files(self.app, self.auth) #enable static files to be fetched self.redis_access = Load_Redis_Access( self.app, self.auth, request) #enable web access for redis operations Load_App_Sys_Files(self.app, self.auth, request, self.file_server_library) self.subsystems = [] self.modules = {} self.load_specified_modules()
""" import os from flask import Flask from flask_httpauth import HTTPDigestAuth import settings import Ice # Create Flask app app = Flask(__name__) app.config['SECRET_KEY'] = os.urandom(24) # Initialize Digest Auth auth = HTTPDigestAuth() # If enabled, all endpoints will be digest auth protected auth_enabled = settings.ENABLE_AUTH # Load up Murmur slice file into Ice Ice.loadSlice('', ['-I' + Ice.getSliceDir(), os.path.join(settings.MURMUR_ROOT, settings.SLICE_FILE)]) import Murmur # Configure Ice properties props = Ice.createProperties() props.setProperty("Ice.ImplicitContext", "Shared") props.setProperty('Ice.Default.EncodingVersion', '1.0') props.setProperty('Ice.MessageSizeMax', str(settings.ICE_MESSAGESIZE)) idata = Ice.InitializationData() idata.properties = props
def open_rosa_default_response(**kwargs): content = '''<?xml version='1.0' encoding='UTF-8'?> <OpenRosaResponse xmlns='http://openrosa.org/http/response'> <message>{}</message> </OpenRosaResponse>'''.format(kwargs.get('content', '')) response = make_response(content, kwargs.get('status_code', 201)) response.headers.extend(make_open_rosa_headers()) return response bp = Blueprint('xforms', __name__, template_folder='templates') participant_auth = HTTPDigestAuth() @participant_auth.verify_opaque def verify_opaque(opaque): return True @participant_auth.verify_nonce def verify_nonce(nonce): return True @participant_auth.get_password def get_pw(participant_id): event = getattr(g, 'event', services.events.default())
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()
LOG_CONNECT_ALLOWED_TMPL, NO_PASSPHRASE, PRIVILEGE_LEVELS, PRIV_IDENTITY, PRIV_DESCRIPTION, PRIV_STATE_TOTALS, PRIV_FULL_READ, PRIV_SHUTDOWN, PRIV_FULL_CONTROL, CONNECT_DENIED_PRIV_TMPL) from OpenSSL import crypto from werkzeug.utils import secure_filename comms_options = 'md5' if AUTHENTICATION_METHOD == 'Basic': from flask_httpauth import HTTPBasicAuth auth = HTTPBasicAuth() elif AUTHENTICATION_METHOD == 'Digest': from flask_httpauth import HTTPDigestAuth auth = HTTPDigestAuth(use_ha1_pw=True) class InvalidUsage(Exception): status_code = 400 def __init__(self, message, status_code=None, payload=None): Exception.__init__(self) self.message = message if status_code is not None: self.status_code = status_code self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message
#!/usr/bin/env python3 from flask import Flask from flask import g from flask_httpauth import HTTPBasicAuth from flask_httpauth import HTTPDigestAuth from flask_httpauth import MultiAuth from werkzeug.security import generate_password_hash, check_password_hash APP = Flask(__name__) APP.config['SECRET_KEY'] = 'secret' BASIC_AUTH = HTTPBasicAuth() DIGEST_AUTH = HTTPDigestAuth() MULTI_AUTH = MultiAuth(DIGEST_AUTH, BASIC_AUTH) @BASIC_AUTH.verify_password def verify_password(username, password): g.user = username return username == 'username' and check_password_hash( generate_password_hash('password'), password) @DIGEST_AUTH.get_password def get_pw(username): if username == 'username': g.user = username return 'password' return None
from flask import Flask,request,Response,g from flask_httpauth import HTTPDigestAuth #authentication import re import sqlite3 app = Flask(__name__) app.config['SECRET_KEY'] = 'SECRET KEY HERE' #question 2 Authentication ------------------------------------ users = { 'aws':'candidate' } auth = HTTPDigestAuth() #authentication @auth.get_password def get_pw(username): if username in users: return users.get(username) else: return "SUCCESS" return None #-------------------------------------------------------------- #question 1---------------------------------------------------- @app.route('/') def hello_world(): return 'AWS' #question 2-----------------------------------------------------
from flask import Blueprint, request, make_response, g, jsonify, redirect, url_for from flask_httpauth import HTTPBasicAuth, HTTPDigestAuth from lms.model.auth import Auth import logging from . import Session auth_api = Blueprint('auth_api', __name__) auth_get = Blueprint('auth_get', __name__) auth_password = HTTPBasicAuth() auth_token = HTTPDigestAuth() logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) # authentication token route @auth_get.route('/get-auth-token') @auth_password.login_required def get_auth_token(): response = make_response(jsonify({'token': g.user.generate_auth_token()})) response.set_cookie('token', g.user.generate_auth_token()) return response, 200 # register new user @auth_get.route('/register', methods=['POST']) def register(): logger.log(logging.INFO, request.form)
def __init__(self, name, redis_handle, redis_new_handle, app_files, sys_files, gm, startup_dict): app = Flask(name) auth = HTTPDigestAuth() auth.get_password(self.get_pw) startup_dict["DEBUG"] = True self.startup_dict = startup_dict self.app = app app.template_folder = 'flask_web_modular_py3/templates' app.static_folder = 'flask_web_modular_py3/static' app.config['SECRET_KEY'] = startup_dict["SECRET_KEY"] app.config["DEBUG"] = True app.debug = True self.users = json.loads(startup_dict["users"]) alarm_queue = AlarmQueue(redis_handle) Load_Static_Files(app, auth) Load_App_Sys_Files(app, auth, request, app_files, sys_files) Load_Redis_Access(app, auth, request, redis_handle) Load_Irrigation_Pages(app, auth, render_template, redis_handle=redis_handle, redis_new_handle=redis_new_handle, request=request, alarm_queue=alarm_queue) Load_ETO_Management(app, auth, request, app_files, sys_files, gm, redis_new_handle, render_template) Load_Site_Data(app, auth, render_template) Load_Configuration_Data(app, auth, render_template, request, app_files, sys_files, redis_handle, redis_new_handle) Load_Streaming_Data(app, auth, render_template, request, app_files, sys_files, redis_handle, redis_new_handle, gm) Load_Linux_Controller_Data(app, auth, request, render_template, redis_new_handle) Load_Statistic_Data(app, auth, render_template, request, app_files, sys_files, redis_handle, redis_new_handle, gm) Load_Process_Control(app, auth, request, render_template, redis_new_handle, redis_handle, gm) Load_Web_Socket_Handler(app, auth, render_template) search_node = gm.match_terminal_relationship("UDP_IO_SERVER")[0] ip = search_node['redis_host'] db = search_node["redis_rpc_db"] logging_key = search_node["logging_key"] redis_rpc_queue = search_node['redis_rpc_key'] redis_rpc_handle = redis.StrictRedis(host=ip, db=db, decode_responses=True) rpc_client = Redis_Rpc_Client(redis_rpc_handle, redis_rpc_queue) # find remote devices search_nodes = gm.match_relationship_list([["UDP_IO_SERVER", None]], starting_set=None, property_values=None, fetch_values=False) remote_lists = gm.match_terminal_relationship( "REMOTE_UNIT", starting_set=search_nodes) address_list = [] for i in remote_lists: address_list.append(i["modbus_address"]) Load_Modbus_Data(app, auth, request, render_template, redis_new_handle, redis_handle, rpc_client, address_list, logging_key)
# # # # # # from datetime import datetime from subprocess import check_output import json import threading import os import re from flask_httpauth import HTTPDigestAuth from functools import wraps import domains.support.models as modLib from flask import session, request, flash, redirect, url_for, Response auth = HTTPDigestAuth(realm="ARMORE", use_ha1_pw=True) defaultCreds = { "armore": auth.generate_ha1("armore", "armore") } @auth.error_handler def secureError(): return Response('<script> window.location.replace("/welcome")</script>', 401, {'WWWAuthenticate':'Digest realm="Login Required"'}) def notAuthorized(): flash("Not Authorized to View This Page") if not request.referrer: return redirect(url_for('.welcome')) return redirect(request.referrer) # Decorator for determining if user is authenticated and authorized to view resource # If 'roles' is a string, resource requires AT LEAST the specified level of authorization