def init_app(app, user_datastore, LoginForm): def load_user(user_id): return user_datastore.get_user(user_id) def load_user_from_request(request): apikey = request.headers.environ.get('HTTP_X_API_KEY', None) if apikey: user = user_datastore.find_user(apikey=apikey) if not user: return None else: auth = request.headers.get('Authorization') if not auth or auth.count(':') != 1: return None login, password = auth.split(':') user = user_datastore.find_user(email=login.strip()) if user is None: return None if not verify_and_update_password(password.strip(), user): return None return user if login_user(user) else None security = Security() security.init_app(app, user_datastore, login_form=LoginForm) app.login_manager.request_loader(load_user_from_request) app.login_manager.user_loader(load_user) user_logged_out.connect(invalidate_user)
def init_app(app): security = Security() security.init_app(app, user_datastore, login_form=LoginForm) app.login_manager.request_loader(load_user_from_request) app.login_manager.user_loader(load_user) user_logged_out.connect(invalidate_user) user_logged_in.connect(invalidate_user)
def init_app(app): login_manager.init_app(app) # provide a landing page that asks the user to login app.route('/login_request')(login_request) # flash notify on login and logout user_logged_in.connect(logged_in, app) # see https://github.com/maxcountryman/flask-login/issues/162 user_logged_out.connect(logged_out, app) _init_mod(app, 'RELENGAPI_AUTHENTICATION', 'browserid', 'relengapi.lib.auth.auth_types') _init_mod(app, 'RELENGAPI_PERMISSIONS', 'static', 'relengapi.lib.auth.perms_types')
def initialize(self): def logOutHandler(sender, **kwargs): self.onLogout() def logInHandler(sender, **kwargs): for key, value in kwargs.iteritems(): if isinstance(value, SessionUser): self.onLogin() self.logOutHandler = logOutHandler self.logInHandler = logInHandler user_logged_in.connect(logInHandler) user_logged_out.connect(logOutHandler)
def init_app(app): login_manager.init_app(app) # provide a landing page that asks the user to login app.route('/login_request')(login_request) # flash notify on login and logout user_logged_in.connect(logged_in, app) # see https://github.com/maxcountryman/flask-login/issues/162 user_logged_out.connect(logged_out, app) auth_type = app.config.get('RELENGAPI_AUTHENTICATION', {}).get('type', 'browserid') app.config['RELENGAPI_AUTHENTICATION_TYPE'] = auth_type # load and initialize the appropriate auth mechanism. Using entry_points # like this avoids even importing plugins this app isn't using entry_points = list( pkg_resources.iter_entry_points('relengapi.auth.mechanisms', auth_type)) if len(entry_points) == 0: raise RuntimeError("no such authentication type %r" % (auth_type, )) elif len(entry_points) > 1: # pragma: no cover raise RuntimeError( "multiple authentication plugins defined for type %r" % (auth_type, )) ep = entry_points[0] plugin_init_app = ep.load() plugin_init_app(app) perms_type = app.config.get('RELENGAPI_PERMISSIONS', {}).get('type', 'static') app.config['RELENGAPI_PERMISSIONS_TYPE'] = perms_type # now load and initialize the appropriate perms mechanism entry_points = list( pkg_resources.iter_entry_points('relengapi.perms.mechanisms', perms_type)) if len(entry_points) == 0: raise RuntimeError("no such permissions type %r" % (perms_type, )) elif len(entry_points) > 1: # pragma: no cover raise RuntimeError("multiple permissions plugins defined for type %r" % (perms_type, )) ep = entry_points[0] plugin_init_app = ep.load() plugin_init_app(app)
def __init__(self, app, blueprint): super(ShibbolethLogin, self).__init__(app, blueprint) if not app.config['SLIDEATLAS_SHIBBOLETH']: # self.enabled is False by default return self.enabled = True blueprint.add_url_rule('/login.shibboleth/<path:handler>', endpoint=self.endpoint_handler, build_only=True) blueprint.add_url_rule('/login/shibboleth', endpoint=self.endpoint, view_func=anonymous_user_required(self.login_view), methods=['GET']) user_logged_out.connect(self.on_logout, app)
def init_app(app): login_manager.init_app(app) # provide a landing page that asks the user to login app.route('/login_request')(login_request) # flash notify on login and logout user_logged_in.connect(logged_in, app) # see https://github.com/maxcountryman/flask-login/issues/162 user_logged_out.connect(logged_out, app) auth_type = app.config.get( 'RELENGAPI_AUTHENTICATION', {}).get('type', 'browserid') app.config['RELENGAPI_AUTHENTICATION_TYPE'] = auth_type # load and initialize the appropriate auth mechanism. Using entry_points # like this avoids even importing plugins this app isn't using entry_points = list( pkg_resources.iter_entry_points('relengapi.auth.mechanisms', auth_type)) if len(entry_points) == 0: raise RuntimeError("no such authentication type %r" % (auth_type,)) elif len(entry_points) > 1: raise RuntimeError( "multiple authentication plugins defined for type %r" % (auth_type,)) ep = entry_points[0] plugin_init_app = ep.load() plugin_init_app(app) perms_type = app.config.get( 'RELENGAPI_PERMISSIONS', {}).get('type', 'static') app.config['RELENGAPI_PERMISSIONS_TYPE'] = perms_type # now load and initialize the appropriate perms mechanism entry_points = list( pkg_resources.iter_entry_points('relengapi.perms.mechanisms', perms_type)) if len(entry_points) == 0: raise RuntimeError("no such permissions type %r" % (perms_type,)) elif len(entry_points) > 1: raise RuntimeError( "multiple permissions plugins defined for type %r" % (perms_type,)) ep = entry_points[0] plugin_init_app = ep.load() plugin_init_app(app)
def initialize(self): self.user = None self.designs = None self.astroprintCloud = None self.cameraManager = None self.materialCounter = None self._printerListener = None def logOutHandler(sender, **kwargs): self.onLogout() def logInHandler(sender, **kwargs): for key, value in kwargs.iteritems(): if isinstance(value, SessionUser): self.onLogin() self.logOutHandler = logOutHandler self.logInHandler = logInHandler user_logged_in.connect(logInHandler) user_logged_out.connect(logOutHandler)
def setup_app(): """Setup OAuth clients.""" # Connect signal to remove access tokens on logout user_logged_out.connect(oauth_logout_handler) # Add remote applications oauth.init_app(current_app) for remote_app, conf in cfg['OAUTHCLIENT_REMOTE_APPS'].items(): # Prevent double creation problems if remote_app not in oauth.remote_apps: remote = oauth.remote_app( remote_app, **conf['params'] ) remote = oauth.remote_apps[remote_app] # Set token getter for remote remote.tokengetter(make_token_getter(remote)) # Register authorized handler handlers.register( remote_app, remote.authorized_handler(make_handler( conf.get('authorized_handler', authorized_default_handler), remote, )) ) # Register disconnect handler disconnect_handlers.register( remote_app, make_handler( conf.get('disconnect_handler', disconnect_handler), remote, with_response=False, ) ) # Register sign-up handlers def dummy_handler(remote, *args, **kargs): pass signup_handler = conf.get('signup_handler', dict()) account_info_handler = make_handler( signup_handler.get('info', dummy_handler), remote, with_response=False ) account_setup_handler = make_handler( signup_handler.get('setup', dummy_handler), remote, with_response=False ) account_view_handler = make_handler( signup_handler.get('view', dummy_handler), remote, with_response=False ) signup_handlers.register( remote_app, dict( info=account_info_handler, setup=account_setup_handler, view=account_view_handler, ) )
auth = Blueprint('auth_blueprint', __name__) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' login_manager.login_message = "" app.register_blueprint(auth) def auditUser(sender, user): entry = AuditEntry(user.username, datetime.now(), 'LOGOUT', 'SUCCESS') db.session.add(entry) db.session.commit() user_logged_out.connect(auditUser, app) @app.context_processor def add_session_config(): """Add current_app.permanent_session_lifetime converted to milliseconds to context. The config variable PERMANENT_SESSION_LIFETIME is not used because it could be either a timedelta object or an integer representing seconds. """ return { 'TIMEOUT_WARNING_MS': ( app.config['TIMEOUT_WARNING_MS']), 'TIMEOUT_LOGOUT_MS' : ( app.config['TIMEOUT_LOGOUT_MS']), 'KEEPALIVE_INTERVAL_MS' : ( app.config['KEEPALIVE_INTERVAL_MS']),
def create_app(settings_override=None, register_security_blueprint=True): """Returns the frontend application instance""" app = factory.create_app(__name__, __path__, settings_override) # Init assets assets.init_app(app) menu.init_app(app) gravatar.init_app(app) userdatastore = MongoEngineUserDatastore(db, models.User, models.Role) security.init_app(app, userdatastore, login_form=DeploymentLoginForm, register_blueprint=register_security_blueprint) app.session_interface = CustomMongoEngineSessionInterface(db) init_admin(admin, app) # Register custom error handlers if not app.debug: for e in [500, 404, 403]: app.errorhandler(e)(handle_error) @app.before_first_request def create_user_roles(): userdatastore.find_or_create_role('clerk') userdatastore.find_or_create_role('manager') userdatastore.find_or_create_role('analyst') userdatastore.find_or_create_role('admin') # permissions services.perms.get_or_create(action='view_events') services.perms.get_or_create(action='view_messages') services.perms.get_or_create(action='view_analyses') services.perms.get_or_create(action='add_submission') services.perms.get_or_create(action='edit_forms') services.perms.get_or_create(action='edit_locations') services.perms.get_or_create(action='edit_participant') services.perms.get_or_create(action='edit_submission') services.perms.get_or_create(action='edit_location') services.perms.get_or_create(action='import_participants') services.perms.get_or_create(action='import_locations') services.perms.get_or_create(action='export_participants') services.perms.get_or_create(action='export_messages') services.perms.get_or_create(action='export_submissions') services.perms.get_or_create(action='export_locations') services.perms.get_or_create(action='send_messages') # register deployment selection middleware app.before_request(set_request_presets) # add Jinja2 filters app.jinja_env.filters.update(custom_filters) # Login and logout signal handlers # user_logged_out.connect(lambda app, user: session.clear()) user_logged_out.connect(clear_session) @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): needs = services.perms.get_all_needs( models.User(**identity.user._data)) for need in needs: identity.provides.add(need) @app.context_processor def inject_permissions(): ga_key = app.config.get('GOOGLE_ANALYTICS_KEY') return dict(perms=permissions, ga_key=ga_key) # clickjacking protection @app.after_request def frame_buster(response): response.headers['X-Frame-Options'] = app.config.get( 'X_FRAME_OPTIONS', 'DENY') return response return app
login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' login_manager.login_message = "" app.register_blueprint(auth) def auditUser(sender, user): entry = AuditEntry(user.username, datetime.now(), 'LOGOUT', 'SUCCESS') db.session.add(entry) db.session.commit() user_logged_out.connect(auditUser, app) @app.context_processor def add_session_config(): """Add current_app.permanent_session_lifetime converted to milliseconds to context. The config variable PERMANENT_SESSION_LIFETIME is not used because it could be either a timedelta object or an integer representing seconds. """ return { 'TIMEOUT_WARNING_MS': (app.config['TIMEOUT_WARNING_MS']), 'TIMEOUT_LOGOUT_MS': (app.config['TIMEOUT_LOGOUT_MS']), 'KEEPALIVE_INTERVAL_MS': (app.config['KEEPALIVE_INTERVAL_MS']), 'SITE_NAME': (app.config['SITE_NAME']), }
from werkzeug.security import generate_password_hash from flask.ext.login import user_logged_in, user_logged_out from .util import * def when_user_logged_in(sender, user, **extra): session['shipper_or_deliverer'] = 1 if hasattr(user, 'sid') else 2 # print "user_logged_in, %s" % session['shipper_or_deliverer'] session.modified = True def when_user_logged_out(sender, user, **extra): del session['shipper_or_deliverer'] session.modified = True user_logged_in.connect(when_user_logged_in, app) user_logged_out.connect(when_user_logged_out, app) @lm.user_loader def load_user(user_id): if session.get('shipper_or_deliverer') == 1: return Shipper.query.get(int(user_id)) elif session.get('shipper_or_deliverer') == 2: return Deliverer.query.get(int(user_id)) else: return None def sendmail(title, body, recipients): ses.send_email( app.config['SES_SENDER_EMAIL'],
def init_signals(app): user_logged_in.connect(on_user_logged_in, app) user_logged_out.connect(on_user_logged_out, app) voucher_generated.connect(on_voucher_generated, app) voucher_logged_in.connect(on_voucher_logged_in, app)
# def log_session_start(app, user): session = LoginSession.new() db.session.add(session) db.session.commit() def log_session_end(app, user): session = LoginSession.query.get_active_for(user) if session: session.ended_at = datetime.utcnow() db.session.commit() user_logged_in.connect(log_session_start) user_logged_out.connect(log_session_end) # login redirect utilities # from http://flask.pocoo.org/snippets/62/ def is_safe_url(target): ref_url = urlparse(request.host_url) test_url = urlparse(urljoin(request.host_url, target)) return test_url.scheme in ('http', 'https') and \ ref_url.netloc == test_url.netloc def get_redirect_target(): for target in (request.values.get('next'), request.referrer): if not target: continue
def create_app(settings_override=None, register_security_blueprint=True): """Returns the frontend application instance""" app = factory.create_app(__name__, __path__, settings_override) # Init assets assets.init_app(app) menu.init_app(app) gravatar.init_app(app) userdatastore = MongoEngineUserDatastore(db, models.User, models.Role) security.init_app(app, userdatastore, login_form=DeploymentLoginForm, register_blueprint=register_security_blueprint) app.session_interface = CustomMongoEngineSessionInterface(db) csrf.init_app(app) init_admin(admin, app) # Register custom error handlers if not app.debug: for e in [500, 404, 403]: app.errorhandler(e)(handle_error) @app.before_first_request def create_user_roles(): userdatastore.find_or_create_role('clerk') userdatastore.find_or_create_role('manager') userdatastore.find_or_create_role('analyst') userdatastore.find_or_create_role('admin') # register deployment selection middleware app.before_request(set_request_presets) # add Jinja2 filters app.jinja_env.filters.update(custom_filters) # Login and logout signal handlers # user_logged_out.connect(lambda app, user: session.clear()) user_logged_out.connect(clear_session) @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): needs = services.perms.get_all_needs( models.User(**identity.user._data)) for need in needs: identity.provides.add(need) @app.context_processor def inject_permissions(): ga_key = app.config.get('GOOGLE_ANALYTICS_KEY') return dict(perms=permissions, ga_key=ga_key) # clickjacking protection @app.after_request def frame_buster(response): response.headers['X-Frame-Options'] = app.config.get( 'X_FRAME_OPTIONS', 'DENY') return response # content security policy @app.after_request def content_security_policy(response): response.headers['Content-Security-Policy'] = "default-src 'self' " + \ "*.googlecode.com *.google-analytics.com *.persona.org " + \ "'unsafe-inline' 'unsafe-eval'; img-src * data:" return response return app