Python flask_login.LoginManager() Examples

The following are 24 code examples of flask_login.LoginManager(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_login , or try the search function .
Example #1
Source Project: flask-security   Author: Flask-Middleware   File: core.py    License: MIT License 6 votes vote down vote up
def _get_login_manager(app, anonymous_user):
    lm = LoginManager()
    lm.anonymous_user = anonymous_user or AnonymousUser
    lm.localize_callback = localize_callback
    lm.login_view = "%s.login" % cv("BLUEPRINT_NAME", app=app)
    lm.user_loader(_user_loader)
    lm.request_loader(_request_loader)

    if cv("FLASH_MESSAGES", app=app):
        lm.login_message, lm.login_message_category = cv("MSG_LOGIN", app=app)
        lm.needs_refresh_message, lm.needs_refresh_message_category = cv(
            "MSG_REFRESH", app=app
        )
    else:
        lm.login_message = None
        lm.needs_refresh_message = None

    lm.init_app(app)
    return lm 
Example #2
Source Project: job-web-demo   Author: zkqiang   File: app.py    License: MIT License 6 votes vote down vote up
def register_extensions(app):
    db.init_app(app)
    Migrate(app, db)
    CKEditor(app)
    Moment(app)
    share = Share()
    share.init_app(app)
    login_manager = LoginManager()
    login_manager.init_app(app)
    configure_uploads(app, uploaded_resume)
    configure_uploads(app, uploaded_logo)
    patch_request_class(app, app.config['UPLOADED_SIZE'])
    login_manager = LoginManager()
    login_manager.init_app(app)

    @login_manager.user_loader
    def user_loader(id):
        if User.query.get(id):
            return User.query.get(id)
        elif Company.query.get(id):
            return Company.query.get(id)
    login_manager.login_view = 'front.login' 
Example #3
Source Project: flask-unchained   Author: briancappello   File: security.py    License: MIT License 6 votes vote down vote up
def _get_login_manager(self,
                           app: FlaskUnchained,
                           anonymous_user: AnonymousUser,
                           ) -> LoginManager:
        """
        Get an initialized instance of Flask Login's
        :class:`~flask_login.LoginManager`.
        """
        login_manager = LoginManager()
        login_manager.anonymous_user = anonymous_user or AnonymousUser
        login_manager.localize_callback = _
        login_manager.request_loader(self._request_loader)
        login_manager.user_loader(
            # skipcq: PYL-W0108 (unnecessary lambda)
            lambda *a, **kw: self.security_utils_service.user_loader(*a, **kw))
        login_manager.login_view = 'security_controller.login'
        login_manager.login_message = _(
            'flask_unchained.bundles.security:error.login_required')
        login_manager.login_message_category = 'info'
        login_manager.needs_refresh_message = _(
            'flask_unchained.bundles.security:error.fresh_login_required')
        login_manager.needs_refresh_message_category = 'info'
        login_manager.init_app(app)
        return login_manager 
Example #4
Source Project: myblog   Author: fushall   File: ext.py    License: GNU General Public License v3.0 6 votes vote down vote up
def register_exts(app: Flask):
    # flask-sqlalchemy
    db.init_app(app)

    # flask-login
    login = LoginManager(app)
    login.login_message = None
    login.login_view = 'admin.login'
    login.user_loader(lambda user_id: get_user(user_id))

    # exts.library
    from . import library
    LibraryManager(app, library)

    # exts.message
    Message(app) 
Example #5
Source Project: flask-vue-todo   Author: frostming   File: __init__.py    License: MIT License 6 votes vote down vote up
def create_app():
    app = Flask(
        __name__, static_folder=os.path.join(FRONTEND_FOLDER, 'dist'),
        template_folder=FRONTEND_FOLDER
    )
    app.config.from_pyfile('settings.py')
    db.init_app(app)
    CSRFProtect(app)
    Migrate(app, db)
    CORS(app)
    lm = LoginManager(app)

    @lm.user_loader
    def load_user(uid):
        return User.query.get(uid)

    @app.route('/')
    def index():
        return render_template('index.html')

    app.register_blueprint(todos.bp, url_prefix="/")
    app.register_blueprint(auth.bp, url_prefix="/auth")
    register_error_handlers(app)
    return app 
Example #6
Source Project: flask-bitmapist   Author: cuttlesoft   File: test_extension.py    License: MIT License 6 votes vote down vote up
def test_flask_login_user_login(app):
    # LoginManager could be set up in app fixture in conftest.py instead
    login_manager = LoginManager()
    login_manager.init_app(app)

    # TODO: once event is marked, user id exists in MonthEvents and test will
    #       continue to pass, regardless of continued success; set to current
    #       microsecond to temporarily circumvent, but there should be a better
    #       way to fix user_id assignment (or tear down redis or something)
    user_id = datetime.now().microsecond

    with app.test_request_context():
        # set up and log in user
        user = User()
        user.id = user_id
        login_user(user)

        # test that user was logged in
        assert current_user.is_active
        assert current_user.is_authenticated
        assert current_user == user

        # test that user id was marked with 'user:logged_in' event
        assert user_id in MonthEvents('user:logged_in', now.year, now.month) 
Example #7
Source Project: floranet   Author: Fluent-networks   File: webserver.py    License: MIT License 6 votes vote down vote up
def __init__(self, server):
        """Initialize the web server.
        
        Args:
            server: NetServer object      
        """
        self.server = server
        self.port = None
        
        # Create Flask app and configure
        self.app = Flask(__name__)
        self.app.config['ERROR_404_HELP'] = False

        # Create REST API instance
        self.restapi = RestApi(self.app, self.server)

        # Create LoginManager instance and configure
        self.login = LoginManager()
        self.login.init_app(self.app)
        self.login.request_loader(self.load_user) 
Example #8
Source Project: sentry-python   Author: getsentry   File: test_flask.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_flask_login_partially_configured(
    sentry_init, app, capture_events, monkeypatch, integration_enabled_params
):
    sentry_init(**integration_enabled_params)

    events = capture_events()

    login_manager = LoginManager()
    login_manager.init_app(app)

    client = app.test_client()
    client.get("/message")

    (event,) = events
    assert event.get("user", {}).get("id") is None 
Example #9
Source Project: open_dnsdb   Author: qunarcorp   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def init_login_manager():
    login_manager = LoginManager()
    login_manager.session_protection = 'strong'
    login_manager.login_view = 'auth.login'

    from dnsdb_common.dal.models.user import User, AnonymousUser
    login_manager.anonymous_user = AnonymousUser

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(int(user_id))

    return login_manager 
Example #10
Source Project: Flask-Blogging   Author: gouthambs   File: test_views.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        FlaskBloggingTestCase.setUp(self)
        self._create_storage()
        self.app.config["BLOGGING_URL_PREFIX"] = "/blog"
        self.app.config["BLOGGING_PLUGINS"] = []
        self.engine = self._create_blogging_engine()
        self.login_manager = LoginManager(self.app)

        @self.login_manager.user_loader
        @self.engine.user_loader
        def load_user(user_id):
            return TestUser(user_id)

        @self.app.route("/login/<username>/", methods=["POST"],
                        defaults={"blogger": 0})
        @self.app.route("/login/<username>/<int:blogger>/", methods=["POST"])
        def login(username, blogger):
            this_user = TestUser(username)
            login_user(this_user)
            if blogger:
                identity_changed.send(current_app._get_current_object(),
                                      identity=Identity(username))
            return redirect("/")

        @self.app.route("/logout/")
        def logout():
            logout_user()
            identity_changed.send(current_app._get_current_object(),
                                  identity=AnonymousIdentity())
            return redirect("/")
        self.pids = []
        for i in range(20):
            tags = ["hello"] if i < 10 else ["world"]
            user = "testuser" if i < 10 else "newuser"
            pid = self.storage.save_post(title="Sample Title%d" % i,
                                         text="Sample Text%d" % i,
                                         user_id=user, tags=tags)
            self.pids.append(pid) 
Example #11
Source Project: Flask-Blogging   Author: gouthambs   File: test_signals.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        FlaskBloggingTestCase.setUp(self)
        self._create_storage()
        self.app.config["BLOGGING_URL_PREFIX"] = "/blog"
        self.app.config["BLOGGING_PLUGINS"] = ["test.plugin"]
        self.engine = self._create_blogging_engine()
        self.login_manager = LoginManager(self.app)

        @self.login_manager.user_loader
        @self.engine.user_loader
        def load_user(user_id):
            return TestUser(user_id)

        @self.app.route("/login/<username>/", methods=["POST"],
                        defaults={"blogger": 0})
        @self.app.route("/login/<username>/<int:blogger>/", methods=["POST"])
        def login(username, blogger):
            this_user = TestUser(username)
            login_user(this_user)
            if blogger:
                identity_changed.send(current_app._get_current_object(),
                                      identity=Identity(username))
            return redirect("/")

        @self.app.route("/logout/")
        def logout():
            logout_user()
            identity_changed.send(current_app._get_current_object(),
                                  identity=AnonymousIdentity())
            return redirect("/")

        for i in range(20):
            tags = ["hello"] if i < 10 else ["world"]
            user = "testuser" if i < 10 else "newuser"
            self.storage.save_post(title="Sample Title%d" % i,
                                   text="Sample Text%d" % i,
                                   user_id=user, tags=tags) 
Example #12
Source Project: ProjectAlice   Author: project-alice-assistant   File: WebInterfaceManager.py    License: GNU General Public License v3.0 5 votes vote down vote up
def flaskLoginManager(self) -> LoginManager:
		return self._flaskLoginManager 
Example #13
Source Project: python-dockerflow   Author: mozilla-services   File: test_flask.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def create_app():
    app = Flask("dockerflow")
    app.secret_key = "super sekrit"
    login_manager = LoginManager(app)
    login_manager.user_loader(load_user)
    return app 
Example #14
Source Project: python-dockerflow   Author: mozilla-services   File: test_flask.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def test_version_path(mocker, version_content):
    app = Flask("dockerflow")
    app.secret_key = "super sekrit"
    login_manager = LoginManager(app)
    login_manager.user_loader(load_user)
    custom_version_path = "/something/extra/ordinary"
    dockerflow = Dockerflow(app, version_path=custom_version_path)
    version_callback = mocker.patch.object(
        dockerflow, "_version_callback", return_value=version_content
    )
    with app.test_client() as test_client:
        response = test_client.get("/__version__")
        assert response.status_code == 200
        assert json.loads(response.data.decode()) == version_content
        version_callback.assert_called_with(custom_version_path) 
Example #15
Source Project: eNMS   Author: eNMS-automation   File: server.py    License: GNU General Public License v3.0 5 votes vote down vote up
def configure_login_manager(self):
        login_manager = LoginManager()
        login_manager.session_protection = "strong"
        login_manager.init_app(self)

        @login_manager.user_loader
        def user_loader(name):
            return db.fetch("user", allow_none=True, name=name)

        @login_manager.request_loader
        def request_loader(request):
            return db.fetch("user", allow_none=True, name=request.form.get("name")) 
Example #16
Source Project: quay   Author: quay   File: fixtures.py    License: Apache License 2.0 5 votes vote down vote up
def app(appconfig, initialized_db):
    """
    Used by pytest-flask plugin to inject a custom app instance for testing.
    """
    app = Flask(__name__)
    login_manager = LoginManager(app)

    @app.errorhandler(model.DataModelException)
    def handle_dme(ex):
        response = jsonify({"message": str(ex)})
        response.status_code = 400
        return response

    @login_manager.user_loader
    def load_user(user_uuid):
        return LoginWrappedDBUser(user_uuid)

    @identity_loaded.connect_via(app)
    def on_identity_loaded_for_test(sender, identity):
        on_identity_loaded(sender, identity)

    Principal(app, use_sessions=False)

    app.url_map.converters["regex"] = RegexConverter
    app.url_map.converters["apirepopath"] = APIRepositoryPathConverter
    app.url_map.converters["repopath"] = RepositoryPathConverter

    app.register_blueprint(api_bp, url_prefix="/api")
    app.register_blueprint(appr_bp, url_prefix="/cnr")
    app.register_blueprint(web, url_prefix="/")
    app.register_blueprint(verbs_bp, url_prefix="/c1")
    app.register_blueprint(v1_bp, url_prefix="/v1")
    app.register_blueprint(v2_bp, url_prefix="/v2")
    app.register_blueprint(webhooks, url_prefix="/webhooks")

    app.config.update(appconfig)

    Userfiles(app)
    Mail(app)

    return app 
Example #17
Source Project: vulyk   Author: mrgambal   File: _social_login.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def init_social_login(app, db) -> None:
    """
    Login manager initialisation.

    :param app: Main application instance
    :type app: flask.Flask
    :param db: MongoDB wrapper instance
    :type db: flask_mongoengine.MongoEngine
    """
    app.register_blueprint(social_auth)
    init_social(app, db)

    login_manager = login.LoginManager()
    login_manager.login_view = 'index'
    login_manager.login_message = ''
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(userid) -> Optional[User]:
        try:
            user = User.objects.get(id=userid)
            if user:
                user.last_login = datetime.datetime.now()
                user.save()
            return user
        except (TypeError, ValueError, User.DoesNotExist):
            return None

    @app.before_request
    def global_user() -> None:
        g.user = login.current_user._get_current_object()

    @app.context_processor
    def inject_user() -> Dict[str, Optional[User]]:
        try:
            return {'user': g.user}
        except AttributeError:
            return {'user': None}

    app.context_processor(backends)
    app.logger.info('Social login subsystem is initialized.') 
Example #18
Source Project: postgresql-audit   Author: kvesteri   File: test_flask_integration.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def login_manager():
    return LoginManager() 
Example #19
Source Project: unshred-tag   Author: dchaplinsky   File: users.py    License: MIT License 5 votes vote down vote up
def init_social_login(app, db):
    app.register_blueprint(social_auth)
    init_social(app, db)

    login_manager = flask_login.LoginManager()
    login_manager.login_view = 'index'
    login_manager.login_message = ''
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(userid):
        try:
            user = User.objects.get(id=userid)
            if user:
                user.last_login = datetime.datetime.now()
                user.save()
            return user
        except (TypeError, ValueError, User.DoesNotExist):
            pass

    @app.before_request
    def global_user():
        g.user = flask_login.current_user

    @app.context_processor
    def inject_user():
        try:
            return {'user': g.user}
        except AttributeError:
            return {'user': None} 
Example #20
Source Project: golem   Author: golemhq   File: __init__.py    License: MIT License 5 votes vote down vote up
def create_app():
    """Call this function to create a Golem GUI app object.
    If called externally (e.g.: from a WSGI server) the cwd
    should be a valid Golem test directory"""
    if not session.testdir:
        testdir = os.getcwd()
        if not test_directory.is_valid_test_directory(testdir):
            sys.exit(errors.invalid_test_directory.format(testdir))
        else:
            session.testdir = testdir
    if not session.settings:
        session.settings = settings_manager.get_global_settings()
    app = Flask(__name__)
    app.secret_key = gui_utils.get_secret_key()
    app.config['SESSION_TYPE'] = 'filesystem'
    app.config['GOLEM_VERSION'] = golem.__version__
    login_manager = LoginManager()
    login_manager.login_view = 'webapp.login'
    login_manager.init_app(app)
    app.register_blueprint(webapp_bp)
    app.register_blueprint(report_bp)
    app.register_blueprint(api_bp)
    app.jinja_env.globals['get_user_projects'] = gui_utils.ProjectsCache.get_user_projects

    @login_manager.user_loader
    def load_user(user_id):
        return user_management.Users.get_user_by_id(user_id)

    @app.before_request
    def before_request():
        g.user = current_user

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('404.html', message=error.description), 404

    return app 
Example #21
Source Project: flask-bitmapist   Author: cuttlesoft   File: test_extension.py    License: MIT License 5 votes vote down vote up
def test_flask_login_user_logout(app):
    login_manager = LoginManager()
    login_manager.init_app(app)

    user_id = datetime.now().microsecond

    with app.test_request_context():
        # set up, log in, and log out user
        user = User()
        user.id = user_id
        login_user(user)
        logout_user()

        # test that user was logged out
        assert not current_user.is_active
        assert not current_user.is_authenticated
        assert not current_user == user

        # test that user id was marked with 'user:logged_out' event
        assert user_id in MonthEvents('user:logged_out', now.year, now.month)


# SQLALCHEMY

# TODO: Instead of sqlalchemy fixture (return: db, User),
#       each test could use sqlalchemy fixture (return:
#       db) and sqlalchemy_user fixture (return: User);
#       tests should use whichever is better practice. 
Example #22
Source Project: watchdog   Author: flipkart-incubator   File: index.py    License: Apache License 2.0 4 votes vote down vote up
def __init__(self):
    # TODO: make auth handler and plugin manager singletons
    Advanced_API.__init__(self)
    Minimal.__init__(self)
    self.minimal = False
    self.auth_handler  = AuthenticationHandler()
    self.plugManager   = PluginManager()
    self.login_manager = LoginManager()
    self.plugManager.loadPlugins()
    self.login_manager.init_app(self.app)
    self.login_manager.user_loader(self.load_user)
    self.redisdb = Configuration.getRedisVendorConnection()

    self.defaultFilters.update({'blacklistSelect': 'on', 'whitelistSelect': 'on',
                                'unlistedSelect': 'show',})
    self.args.update({'minimal': False})
    self.pluginArgs = {"current_user":   current_user, "plugin_manager": self.plugManager}

    routes = [{'r': '/cve/<cveid>',                             'm': ['GET'],  'f': self.cve},
              {'r': '/_get_plugins',                            'm': ['GET'],  'f': self._get_plugins},
              {'r': '/plugin/_get_cve_actions',                 'm': ['GET'],  'f': self._get_cve_actions},
              {'r': '/plugin/<plugin>',                         'm': ['GET'],  'f': self.openPlugin},
              {'r': '/plugin/<plugin>/subpage/<page>',          'm': ['GET'],  'f': self.openPluginSubpage},
              {'r': '/plugin/<plugin>/_cve_action/<action>',    'm': ['GET'],  'f': self._jsonCVEAction},
              {'r': '/login',                                   'm': ['POST'], 'f': self.login_check},
              {'r': '/logout',                                  'm': ['POST'], 'f': self.logout},
              {'r': '/admin',                                   'm': ['GET'],  'f': self.admin},
              {'r': '/admin/',                                  'm': ['GET'],  'f': self.admin},
              {'r': '/admin/change_pass',                       'm': ['GET'],  'f': self.change_pass},
              {'r': '/admin/request_token',                     'm': ['GET'],  'f': self.request_token},
              {'r': '/admin/updatedb',                          'm': ['GET'],  'f': self.updatedb},
              {'r': '/admin/whitelist/import',                  'm': ['POST'], 'f': self.listImport},
              {'r': '/admin/blacklist/import',                  'm': ['POST'], 'f': self.listImport},
              {'r': '/admin/whitelist/export',                  'm': ['GET'],  'f': self.listExport},
              {'r': '/admin/blacklist/export',                  'm': ['GET'],  'f': self.listExport},
              {'r': '/admin/whitelist/drop',                    'm': ['POST'], 'f': self.listDrop},
              {'r': '/admin/blacklist/drop',                    'm': ['POST'], 'f': self.listDrop},
              {'r': '/admin/whitelist',                         'm': ['GET'],  'f': self.listView},
              {'r': '/admin/blacklist',                         'm': ['GET'],  'f': self.listView},
              {'r': '/admin/addToList',                         'm': ['GET'],  'f': self.listAdd},
              {'r': '/admin/removeFromList',                    'm': ['GET'],  'f': self.listRemove},
              {'r': '/admin/editInList',                        'm': ['GET'],  'f': self.listEdit},
              {'r': '/admin/listmanagement',                    'm': ['GET'],  'f': self.listManagement},
              {'r': '/admin/listmanagement/<vendor>',           'm': ['GET'],  'f': self.listManagement},
              {'r': '/admin/listmanagement/<vendor>/<product>', 'm': ['GET'],  'f': self.listManagement},
              {'r': '/admin/listmanagement/add',                'm': ['GET'],  'f': self.listManagementAdd},
              {'r': '/login',                                   'm': ['POST'], 'f': self.login_check}]
    for route in routes: self.addRoute(route)


  #############
  # Functions #
  ############# 
Example #23
Source Project: specter-desktop   Author: cryptoadvance   File: server.py    License: MIT License 4 votes vote down vote up
def init_app(app, hwibridge=False, specter=None):
    '''  see blogpost 19nd Feb 2020 '''
    app.logger.info("Initializing QRcode")
    # Login via Flask-Login
    app.logger.info("Initializing LoginManager")
    if specter == None:
        # the default. If not None, then it got injected for testing
        app.logger.info("Initializing Specter")
        specter = Specter(DATA_FOLDER)

    login_manager = LoginManager()
    login_manager.init_app(app) # Enable Login
    login_manager.login_view = "login" # Enable redirects if unauthorized
    @login_manager.user_loader
    def user_loader(id):
        return User.get_user(specter, id)

    def login(id):
        login_user(user_loader(id))
    
    app.login = login
    # Attach specter instance so child views (e.g. hwi) can access it
    app.specter = specter
    if specter.config.get('auth') == "none":
        app.logger.info("Login disabled")
        app.config["LOGIN_DISABLED"] = True
    else:
        app.logger.info("Login enabled")
    app.logger.info("Initializing Controller ...")
    app.register_blueprint(hwi_server, url_prefix='/hwi')
    if not hwibridge:
        with app.app_context():
            from cryptoadvance.specter import controller
            if app.config.get("TESTING") and len(app.view_functions) <=3 :
                # Need to force a reload as otherwise the import is skipped
                # in pytest, the app is created anew for ech test
                # But we shouldn't do that if not necessary as this would result in
                # --> View function mapping is overwriting an existing endpoint function
                import importlib
                importlib.reload(controller)
    else:
        @app.route("/", methods=["GET"])
        def index():
            return redirect('/hwi/settings')
    return app 
Example #24
Source Project: ProjectAlice   Author: project-alice-assistant   File: WebInterfaceManager.py    License: GNU General Public License v3.0 4 votes vote down vote up
def onStart(self):
		super().onStart()
		if not self.ConfigManager.getAliceConfigByName('webInterfaceActive'):
			self.logInfo('Web interface is disabled by settings')
		else:
			langFile = Path(self.Commons.rootDir(), f'core/interface/languages/{self.LanguageManager.activeLanguage.lower()}.json')

			if not langFile.exists():
				self.logWarning(f'Lang "{self.LanguageManager.activeLanguage.lower()}" not found, falling back to "en"')
				langFile = Path(self.Commons.rootDir(), 'core/interface/languages/en.json')
			else:
				self.logInfo(f'Loaded interface in "{self.LanguageManager.activeLanguage.lower()}"')

			key = ''.join([random.choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(20)])
			self.app.secret_key = key.encode()
			self._flaskLoginManager = LoginManager()
			self._flaskLoginManager.init_app(self.app)
			self._flaskLoginManager.user_loader(self.UserManager.getUserById)
			self._flaskLoginManager.login_view = '/adminAuth/'

			with langFile.open('r') as f:
				self._langData = json.load(f)

			for view in self._VIEWS:
				try:
					view.register(self.app)
				except Exception as e:
					self.logInfo(f'Exception while registering view: {e}')
					continue

			for api in self._APIS:
				try:
					api.register(self.app)
				except Exception as e:
					self.logInfo(f'Exception while registering api endpoint: {e}')
					continue

			self.ThreadManager.newThread(
				name='WebInterface',
				target=self.app.run,
				kwargs={
					'debug': True,
					'port': int(self.ConfigManager.getAliceConfigByName('webInterfacePort')),
					'host': self.Commons.getLocalIp(),
					'use_reloader': False
				}
			)