def passive_login(): logger = logging.getLogger(__name__) if octoprint.server.userManager.enabled: user = octoprint.server.userManager.login_user(flask_login.current_user) else: user = flask_login.current_user remote_address = get_remote_address(flask.request) ip_check_enabled = settings().getBoolean(["server", "ipCheck", "enabled"]) ip_check_trusted = settings().get(["server", "ipCheck", "trustedSubnets"]) if user is not None and not user.is_anonymous() and user.is_active(): flask_principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask_principal.Identity(user.get_id())) if hasattr(user, "session"): flask.session["usersession.id"] = user.session flask.g.user = user logger.info("Passively logging in user {} from {}".format(user.get_id(), remote_address)) response = user.asDict() response["_is_external_client"] = ip_check_enabled and not is_lan_address(remote_address, additional_private=ip_check_trusted) return flask.jsonify(response) elif settings().getBoolean(["accessControl", "autologinLocal"]) \ and settings().get(["accessControl", "autologinAs"]) is not None \ and settings().get(["accessControl", "localNetworks"]) is not None \ and not "active_logout" in flask.request.cookies: autologin_as = settings().get(["accessControl", "autologinAs"]) local_networks = _local_networks() logger.debug("Checking if remote address {} is in localNetworks ({!r})".format(remote_address, local_networks)) try: if netaddr.IPAddress(remote_address) in local_networks: user = octoprint.server.userManager.findUser(autologin_as) if user is not None and user.is_active(): user = octoprint.server.userManager.login_user(user) flask.session["usersession.id"] = user.session flask.g.user = user flask_login.login_user(user) flask_principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask_principal.Identity(user.get_id())) logger.info("Passively logging in user {} from {} via autologin".format(user.get_id(), remote_address)) response = user.asDict() response["_is_external_client"] = ip_check_enabled and not is_lan_address(remote_address, additional_private=ip_check_trusted) return flask.jsonify(response) except: logger.exception("Could not autologin user {} for networks {}".format(autologin_as, local_networks)) return "", 204
def login(u): # login known user if not u.is_anonymous: u = octoprint.server.userManager.login_user(u) flask_login.login_user(u) flask_principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask_principal.Identity(u.get_id())) if hasattr(u, "session"): flask.session["usersession.id"] = u.session flask.g.user = u return u
def loginUser(user, remember=False): """ Logs the provided ``user`` into Flask Login and Principal if not None and active Args: user: the User to login. May be None in which case the login will fail remember: Whether to set the ``remember`` flag on the Flask Login operation Returns: (bool) True if the login succeeded, False otherwise """ if user is not None and user.is_active() and flask_login.login_user(user, remember=remember): flask_principal.identity_changed.send(_flask.current_app._get_current_object(), identity=flask_principal.Identity(user.get_id())) return True return False
def loginFromApiKeyRequestHandler(): """ ``before_request`` handler for blueprints which creates a login session for the provided api key (if available) UI_API_KEY and app session keys are handled as anonymous keys here and ignored. """ apikey = get_api_key(_flask.request) if apikey and apikey != octoprint.server.UI_API_KEY and not octoprint.server.appSessionManager.validate(apikey): user = get_user_for_apikey(apikey) if user is not None and not user.is_anonymous and flask_login.login_user(user, remember=False): flask_principal.identity_changed.send(_flask.current_app._get_current_object(), identity=flask_principal.Identity(user.get_id())) else: return _flask.make_response("Invalid API key", 401)
def load_identity(): if not hasattr(g, "current_user") or not g.current_user: logging.debug("User identity as Anonymous") return p.AnonymousIdentity() identity = p.Identity(g.current_user.id) identity.user = g.current_user logging.debug("Current user %s %d " % (g.current_user.name, g.current_user.id)) identity.provides.add(p.UserNeed(g.current_user.id)) if g.current_user.permissions.count(): for role in g.current_user.permissions: identity.provides.add(p.RoleNeed(role.name.upper())) logging.debug( "User has permissions: %s" % (", ".join([role.name for role in g.current_user.permissions]))) else: logging.debug("User Has no permissions") pass return identity
def passive_login(): logger = logging.getLogger(__name__) user = flask_login.current_user remote_address = get_remote_address(flask.request) ip_check_enabled = settings().getBoolean(["server", "ipCheck", "enabled"]) ip_check_trusted = settings().get(["server", "ipCheck", "trustedSubnets"]) if isinstance(user, LocalProxy): # noinspection PyProtectedMember user = user._get_current_object() def login(u): # login known user if not u.is_anonymous: u = octoprint.server.userManager.login_user(u) flask_login.login_user(u) flask_principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask_principal.Identity(u.get_id())) if hasattr(u, "session"): flask.session["usersession.id"] = u.session flask.g.user = u return u if user is not None and user.is_active: # login known user logger.info("Passively logging in user {} from {}".format(user.get_id(), remote_address)) user = login(user) elif settings().getBoolean(["accessControl", "autologinLocal"]) \ and settings().get(["accessControl", "autologinAs"]) is not None \ and settings().get(["accessControl", "localNetworks"]) is not None: autologin_as = settings().get(["accessControl", "autologinAs"]) local_networks = _local_networks() try: if netaddr.IPAddress(remote_address) in local_networks: autologin_user = octoprint.server.userManager.findUser(autologin_as) if autologin_user is not None and autologin_user.is_active: autologin_user = octoprint.server.userManager.login_user(autologin_user) logger.info("Passively logging in user {} from {} via autologin".format(user.get_id(), local_networks)) user = login(autologin_user) if netaddr.IPAddress(remote_address) in local_networks: user = octoprint.server.userManager.findUser(autologin_as) if user is not None and user.is_active(): user = octoprint.server.userManager.login_user(user) flask.session["usersession.id"] = user.session flask.g.user = user flask_login.login_user(user) flask_principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask_principal.Identity(user.get_id())) logger.info("Passively logging in user {} from {} via autologin".format(user.get_id(), remote_address)) response = user.asDict() response["_is_external_client"] = ip_check_enabled and not is_lan_address(remote_address, additional_private=ip_check_trusted) return flask.jsonify(response) except Exception: logger.exception("Could not autologin user {} for networks {}".format(autologin_as, local_networks)) response = user.as_dict() response["_is_external_client"] = ip_check_enabled and not is_lan_address(remote_address, additional_private=ip_check_trusted) return flask.jsonify(response)
def get_identity(): if 'saml' in flask.session: return flask_principal.Identity(flask.session['saml']['subject']) else: return flask_principal.AnonymousIdentity()
def dispatch_request(self): """ Mandatory interface required by the :py:func:`flask.views.View.dispatch_request`. Will be called by the *Flask* framework to service the request. """ form = LoginForm() if form.validate_on_submit(): try: user = self.fetch(form.login.data.get_id()) if not user.enabled: self.flash( flask.Markup( gettext( 'Please be aware, that the account for user <strong>%(login)s (%(name)s)</strong> is currently disabled.', login=user.login, name=user.fullname)), mydojo.const.FLASH_WARNING) flask_login.login_user(user) # Tell Flask-Principal the identity changed. Access to private method # _get_current_object is according to the Flask documentation: # http://flask.pocoo.org/docs/1.0/reqcontext/#notes-on-proxies flask_principal.identity_changed.send( flask.current_app._get_current_object(), # pylint: disable=locally-disabled,protected-access identity=flask_principal.Identity(user.get_id())) self.flash( flask.Markup( gettext( 'You have been successfully logged in as <strong>%(user)s</strong>.', user=str(user))), mydojo.const.FLASH_SUCCESS) self.logger.info( "User '{}' successfully logged in with 'auth_dev'.".format( user.login)) # Redirect user back to original page. return self.redirect(default_url=flask.url_for( flask.current_app.config['MYDOJO_LOGIN_REDIRECT'])) except sqlalchemy.orm.exc.MultipleResultsFound: self.logger.error( "Multiple results found for user login '{}'.".format( form.login.data)) self.abort(500) except sqlalchemy.orm.exc.NoResultFound: self.flash( gettext('You have entered wrong login credentials.'), mydojo.const.FLASH_FAILURE) except Exception: # pylint: disable=locally-disabled,broad-except self.flash( flask.Markup( gettext( "Unable to perform developer login as <strong>%(user)s</strong>.", user=str(form.login.data))), mydojo.const.FLASH_FAILURE) flask.current_app.log_exception_with_label( traceback.TracebackException(*sys.exc_info()), 'Unable to perform developer login.', ) self.response_context.update(form=form, next=mydojo.forms.get_redirect_target()) return self.generate_response()
def login_user(user, remember=True): flask_login.login_user(user, remember=remember) flask_principal.identity_changed.send( current_app._get_current_object(), identity=flask_principal.Identity(user.id) )
def dispatch_request(self): """ Mandatory interface required by the :py:func:`flask.views.View.dispatch_request`. Will be called by the *Flask* framework to service the request. """ if flask_login.current_user.is_authenticated: return self.redirect( default_url = flask.url_for( flask.current_app.config['MYDOJO_LOGIN_REDIRECT'] ) ) form = LoginForm() if form.validate_on_submit(): try: user = self.fetch(form.login.data) # Check for password validity. if user.check_password(form.password.data): # User account must be enabled. if not user.enabled: self.flash( flask.Markup(gettext( 'Your user account <strong>%(login)s (%(name)s)</strong> is currently disabled, you are not permitted to log in.', login = user.login, name = user.fullname )), mydojo.const.FLASH_FAILURE ) self.abort(403) flask_login.login_user(user) # Mark the login time into database. user.logintime = datetime.datetime.utcnow() self.dbsession.commit() # Tell Flask-Principal the identity changed. Access to private method # _get_current_object is according to the Flask documentation: # http://flask.pocoo.org/docs/1.0/reqcontext/#notes-on-proxies flask_principal.identity_changed.send( flask.current_app._get_current_object(), # pylint: disable=locally-disabled,protected-access identity = flask_principal.Identity(user.get_id()) ) self.flash( flask.Markup(gettext( 'You have been successfully logged in as <strong>%(login)s (%(name)s)</strong>.', login = user.login, name = user.fullname )), mydojo.const.FLASH_SUCCESS ) self.logger.info( "User '{}' successfully logged in with 'auth_pwd'.".format( user.login ) ) # Redirect user back to original page. return self.redirect( default_url = flask.url_for( flask.current_app.config['MYDOJO_LOGIN_REDIRECT'] ) ) # Warn about invalid credentials in case of invalid password. Do # not say specifically it was password, that was invalid. self.flash( gettext('You have entered wrong login credentials.'), mydojo.const.FLASH_FAILURE ) except sqlalchemy.orm.exc.MultipleResultsFound: self.logger.error( "Multiple results found for user login '{}'.".format( form.login.data ) ) self.abort(500) except sqlalchemy.orm.exc.NoResultFound: self.flash( gettext('You have entered wrong login credentials.'), mydojo.const.FLASH_FAILURE ) except Exception: # pylint: disable=locally-disabled,broad-except self.flash( flask.Markup(gettext( "Unable to perform password login as <strong>%(user)s</strong>.", user = str(form.login.data) )), mydojo.const.FLASH_FAILURE ) flask.current_app.log_exception_with_label( traceback.TracebackException(*sys.exc_info()), 'Unable to perform password login.', ) self.response_context.update( form = form, next = mydojo.forms.get_redirect_target() ) return self.generate_response()