diff --git a/src/octoprint/plugins/forcelogin/__init__.py b/src/octoprint/plugins/forcelogin/__init__.py index 0f6ea9cdd..8e6914a55 100644 --- a/src/octoprint/plugins/forcelogin/__init__.py +++ b/src/octoprint/plugins/forcelogin/__init__.py @@ -33,11 +33,25 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin, # ACL hasn't been configured yet, make an exception return False + from octoprint.server.util import loginUserFromApiKey, loginUserFromAuthorizationHeader, InvalidApiKeyException from octoprint.server.util.flask import passive_login + # first try to login via api key & authorization header, just in case that's set + try: + if loginUserFromApiKey(): + # successful? No need for handling the UI + return False + except InvalidApiKeyException: + pass # ignored + + if loginUserFromAuthorizationHeader(): + # successful? No need for handling the UI + return False + + # then try a passive login result = passive_login() if hasattr(result, "status_code") and result.status_code == 200: - # passive login successful, no need to handle that + # successful? No need for handling the UI return False else: return True diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index c2df7ea30..d6610864a 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -59,33 +59,46 @@ def loginFromApiKeyRequestHandler(): UI_API_KEY and app session keys are handled as anonymous keys here and ignored. """ - - apikey = get_api_key(_flask.request) - - if not apikey: - return - - if apikey == octoprint.server.UI_API_KEY: - return - - if octoprint.server.appSessionManager.validate(apikey): - return - - user = get_user_for_apikey(apikey) - if not loginUser(user): + try: + if loginUserFromApiKey(): + _flask.g.login_via_apikey = True + except InvalidApiKeyException: return _flask.make_response("Invalid API key", 403) - _flask.g.login_via_apikey = True - def loginFromAuthorizationHeaderRequestHandler(): """ ``before_request`` handler for creating login sessions based on the Authorization header. """ + loginUserFromApiKey() + +class InvalidApiKeyException(Exception): pass + + +def loginUserFromApiKey(): + apikey = get_api_key(_flask.request) + + if not apikey: + return False + + if apikey == octoprint.server.UI_API_KEY: + return False + + if octoprint.server.appSessionManager.validate(apikey): + return False + + user = get_user_for_apikey(apikey) + if not loginUser(user): + raise InvalidApiKeyException() + else: + return True + + +def loginUserFromAuthorizationHeader(): authorization_header = get_authorization_header(_flask.request) user = get_user_for_authorization_header(authorization_header) - loginUser(user) + return loginUser(user) def loginUser(user, remember=False):