openwebrx-clone/owrx/controllers/admin.py

57 lines
1.9 KiB
Python
Raw Permalink Normal View History

2021-05-03 21:22:28 +00:00
from owrx.controllers.session import SessionStorage
2021-02-08 16:09:22 +00:00
from owrx.users import UserList
2020-04-25 23:54:48 +00:00
from urllib import parse
2021-05-03 21:22:28 +00:00
from http.cookies import SimpleCookie
2020-04-25 23:54:48 +00:00
import logging
logger = logging.getLogger(__name__)
2020-02-23 18:23:18 +00:00
class Authentication(object):
def getUser(self, request):
2021-02-08 16:09:22 +00:00
if "owrx-session" not in request.cookies:
return None
2021-05-03 21:07:27 +00:00
session_id = request.cookies["owrx-session"].value
storage = SessionStorage.getSharedInstance()
session = storage.getSession(session_id)
2021-02-08 16:09:22 +00:00
if session is None:
return None
2021-02-08 16:09:22 +00:00
if "user" not in session:
return None
2021-02-08 16:09:22 +00:00
userList = UserList.getSharedInstance()
2021-05-03 21:07:27 +00:00
user = None
2021-02-08 16:09:22 +00:00
try:
2021-05-03 21:07:27 +00:00
user = userList[session["user"]]
storage.prolongSession(session_id)
2021-02-08 16:09:22 +00:00
except KeyError:
2021-05-03 21:07:27 +00:00
pass
return user
2020-02-23 18:23:18 +00:00
class AuthorizationMixin(object):
2020-02-23 18:23:18 +00:00
def __init__(self, handler, request, options):
self.authentication = Authentication()
self.user = self.authentication.getUser(request)
2020-02-23 18:23:18 +00:00
super().__init__(handler, request, options)
def isAuthorized(self):
return self.user is not None and self.user.is_enabled() and not self.user.must_change_password
2020-02-23 18:23:18 +00:00
def handle_request(self):
if self.isAuthorized():
2020-02-23 18:23:18 +00:00
super().handle_request()
else:
2021-05-03 21:22:28 +00:00
cookie = SimpleCookie()
cookie["owrx-session"] = ""
cookie["owrx-session"]["expires"] = "Thu, 01 Jan 1970 00:00:00 GMT"
self.set_response_cookies(cookie)
if (
"x-requested-with" in self.request.headers
and self.request.headers["x-requested-with"] == "XMLHttpRequest"
):
self.send_response("{}", code=403)
else:
2021-04-18 13:59:05 +00:00
target = "{}login?{}".format(self.get_document_root(), parse.urlencode({"ref": self.request.path[1:]}))
self.send_redirect(target)