A corporation manager and dashboard for EVE Online
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

326 lines
12 KiB

  1. # -*- coding: utf-8 -*-
  2. from datetime import datetime, timedelta, timezone
  3. from flask import g, session, url_for
  4. from itsdangerous import BadSignature, URLSafeSerializer
  5. from . import baseLogger
  6. from .exceptions import AccessDeniedError
  7. __all__ = ["AuthManager"]
  8. _SCOPES = ["publicData", "characterAssetsRead"] # ...
  9. class AuthManager:
  10. """Authentication manager. Handles user access and management."""
  11. EXPIRY_THRESHOLD = 30
  12. def __init__(self, config, eve):
  13. self._config = config
  14. self._eve = eve
  15. self._logger = baseLogger.getChild("auth")
  16. self._debug = self._logger.debug
  17. def _allocate_new_session(self):
  18. """Create a new session for the current user."""
  19. sid, created = g.db.new_session()
  20. session["id"] = sid
  21. session["date"] = int(created.replace(tzinfo=timezone.utc).timestamp())
  22. self._debug("Allocated session id=%d", sid)
  23. g._session_check = True
  24. g._session_expired = False
  25. def _get_session_id(self):
  26. """Return the current session ID, allocating a new one if necessary."""
  27. if "id" not in session:
  28. self._allocate_new_session()
  29. return session["id"]
  30. def _invalidate_session(self):
  31. """Mark the current session as invalid.
  32. Remove it from the database and from the user's cookies.
  33. """
  34. if "id" in session:
  35. sid = session["id"]
  36. g.db.drop_session(sid)
  37. self._debug("Dropped session id=%d", sid)
  38. session.clear()
  39. def _expire_session(self, always_notify=False):
  40. """Mark the current session as expired, then invalidate it."""
  41. if always_notify or session.get("expire-notify"):
  42. g._session_expired = True
  43. self._debug("Session expired id=%d", session["id"])
  44. self._invalidate_session()
  45. def _check_session(self, always_notify_expired=False):
  46. """Return whether the user has a valid, non-expired session.
  47. This checks for the session existing in the database, but does not
  48. check that the user is logged in or has any particular access roles.
  49. """
  50. if "id" not in session:
  51. return False
  52. if hasattr(g, "_session_check"):
  53. return g._session_check
  54. if "date" not in session:
  55. self._debug("Clearing dateless session id=%d", session["id"])
  56. session.clear()
  57. return False
  58. created = g.db.has_session(session["id"])
  59. if not created:
  60. self._expire_session(always_notify=always_notify_expired)
  61. g._session_check = False
  62. return False
  63. cstamp = int(created.replace(tzinfo=timezone.utc).timestamp())
  64. if session["date"] != cstamp:
  65. self._debug("Clearing bad-date session id=%d", session["id"])
  66. session.clear()
  67. return False
  68. g._session_check = True
  69. return True
  70. def _get_state_hash(self):
  71. """Return a hash of the user's session ID suitable for OAuth2 state.
  72. Allocates a new session ID if necessary.
  73. """
  74. key = self._config.get("auth.session_key")
  75. serializer = URLSafeSerializer(key)
  76. return serializer.dumps(self._get_session_id())
  77. def _verify_state_hash(self, state):
  78. """Confirm that a state hash is correct for the user's session.
  79. Assumes we've already checked the session ID. If the state is invalid,
  80. the session will be invalidated.
  81. """
  82. key = self._config.get("auth.session_key")
  83. serializer = URLSafeSerializer(key)
  84. try:
  85. value = serializer.loads(state)
  86. except BadSignature:
  87. self._debug("Bad signature for session id=%d", session["id"])
  88. self._invalidate_session()
  89. return False
  90. if value != session["id"]:
  91. self._debug("Got session id=%d, expected id=%d", value,
  92. session["id"])
  93. self._invalidate_session()
  94. return False
  95. return True
  96. def _fetch_new_token(self, code, refresh=False):
  97. """Given an auth code or refresh token, get a new token and other data.
  98. If refresh is True, code should be a refresh token, otherwise an auth
  99. code. If successful, we'll return a 5-tuple of (access_token,
  100. token_expiry, refresh_token, char_id, char_name). If the token was
  101. invalid, we'll return None. We may also raise EVEAPIError if there was
  102. an internal API error.
  103. """
  104. cid = self._config.get("auth.client_id")
  105. secret = self._config.get("auth.client_secret")
  106. result = self._eve.sso.get_access_token(cid, secret, code, refresh)
  107. if not result:
  108. return None
  109. token, expiry, refresh = result
  110. expires = (datetime.utcnow().replace(microsecond=0) +
  111. timedelta(seconds=expiry))
  112. result = self._eve.sso.get_character_info(token)
  113. if not result:
  114. return None
  115. char_id, char_name = result
  116. return token, expires, refresh, char_id, char_name
  117. def _get_token(self, cid):
  118. """Return a valid access token for the given character, or None.
  119. If the database doesn't have an auth entry for this character, return
  120. None. If the database's token is expired but the refresh token is
  121. valid, then refresh it, update the database, and return the new token.
  122. If the token has become invalid and couldn't be refreshed, drop the
  123. auth information from the database and return None.
  124. """
  125. result = g.db.get_auth(cid)
  126. if not result:
  127. self._debug("No auth info in database for char id=%d", cid)
  128. return None
  129. token, expires, refresh = result
  130. seconds_til_expiry = (expires - datetime.utcnow()).total_seconds()
  131. if seconds_til_expiry >= self.EXPIRY_THRESHOLD:
  132. self._debug("Using cached access token for char id=%d", cid)
  133. return token
  134. result = self._fetch_new_token(refresh, refresh=True)
  135. if not result:
  136. self._debug("Couldn't refresh token for char id=%d", cid)
  137. g.db.drop_auth(cid)
  138. return None
  139. token, expires, refresh, char_id, char_name = result
  140. if char_id != cid:
  141. self._debug("Refreshed token has incorrect char id=%d for "
  142. "char id=%d", char_id, cid)
  143. g.db.drop_auth(cid)
  144. return None
  145. self._debug("Using fresh access token for char id=%d", cid)
  146. g.db.put_character(cid, char_name)
  147. g.db.update_auth(cid, token, expires, refresh)
  148. return token
  149. def _check_access(self, token, char_id):
  150. """"Check whether the given character is allowed to access this site.
  151. If allowed, do nothing. If not, raise AccessDeniedError.
  152. """
  153. resp = self._eve.esi(token).v3.characters(char_id).get()
  154. if resp.get("corporation_id") != self._config.get("corp.id"):
  155. self._debug("Access denied per corp membership for char id=%d "
  156. "session id=%d", char_id, session["id"])
  157. g.db.drop_auth(char_id)
  158. self._invalidate_session()
  159. raise AccessDeniedError()
  160. def get_character_id(self):
  161. """Return the character ID associated with the current session.
  162. Returns None if the session is invalid or is not associated with a
  163. character.
  164. """
  165. if not self._check_session():
  166. return None
  167. if not hasattr(g, "_character_id"):
  168. g._character_id = g.db.read_session(session["id"])
  169. return g._character_id
  170. def get_character_prop(self, prop):
  171. """Look up a property for the current session's character.
  172. Returns None if the session is invalid, is not associated with a
  173. character, or the property has no non-default value.
  174. """
  175. cid = self.get_character_id()
  176. if not cid:
  177. return None
  178. if not hasattr(g, "_character_props"):
  179. g._character_props = g.db.read_character(cid)
  180. return g._character_props.get(prop)
  181. def set_character_style(self, style):
  182. """Update the current user's style and return whether successful."""
  183. cid = self.get_character_id()
  184. if not cid:
  185. return False
  186. style = style.strip().lower()
  187. if style not in self._config.get("style.enabled"):
  188. return False
  189. self._debug("Setting style to %s for char id=%d", style, cid)
  190. g.db.update_character(cid, "style", style)
  191. if hasattr(g, "_character_props"):
  192. delattr(g, "_character_props")
  193. return True
  194. def is_authenticated(self):
  195. """Return whether the user has permission to access this site.
  196. We confirm that they have a valid, non-expired session that is
  197. associated with a character that is permitted to be here.
  198. EVEAPIError or AccessDeniedError may be raised.
  199. """
  200. cid = self.get_character_id()
  201. if not cid:
  202. return False
  203. self._debug("Checking auth for session id=%d", session["id"])
  204. token = self._get_token(cid)
  205. if not token:
  206. self._debug("No valid token for char id=%d session id=%d", cid,
  207. session["id"])
  208. self._invalidate_session()
  209. return False
  210. self._check_access(token, cid)
  211. self._debug("Access granted for char id=%d session id=%d", cid,
  212. session["id"])
  213. g.db.touch_session(session["id"])
  214. return True
  215. def make_login_link(self):
  216. """Return a complete EVE SSO link that the user can use to log in."""
  217. cid = self._config.get("auth.client_id")
  218. target = url_for("login", _external=True, _scheme=self._config.scheme)
  219. scopes = _SCOPES
  220. state = self._get_state_hash()
  221. return self._eve.sso.get_authorize_url(cid, target, scopes, state)
  222. def handle_login(self, code, state):
  223. """Given an OAuth2 code and state, try to authenticate the user.
  224. If the user has a legitimate session and the state is valid, we'll
  225. check the code with EVE SSO to fetch an authentication token. If the
  226. token corresponds to a character that is allowed to access the site,
  227. we'll update their session to indicate so.
  228. Return whether authentication was successful. EVEAPIError or
  229. AccessDeniedError may be raised.
  230. """
  231. if not code or not state:
  232. return False
  233. if "id" in session:
  234. self._debug("Logging in session id=%d", session["id"])
  235. if not self._check_session(always_notify_expired=True):
  236. return False
  237. if not self._verify_state_hash(state):
  238. return False
  239. sid = session["id"]
  240. result = self._fetch_new_token(code)
  241. if not result:
  242. self._debug("Couldn't fetch token for session id=%d", sid)
  243. self._invalidate_session()
  244. return False
  245. token, expires, refresh, char_id, char_name = result
  246. self._check_access(token, char_id)
  247. self._debug("Logged in char id=%d session id=%d", char_id, sid)
  248. g.db.put_character(char_id, char_name)
  249. g.db.set_auth(char_id, token, expires, refresh)
  250. g.db.attach_session(sid, char_id)
  251. g.db.touch_session(sid)
  252. session["expire-notify"] = True
  253. return True
  254. def handle_logout(self):
  255. """Log out the user if they are logged in.
  256. Invalidates their session and clears the session cookie.
  257. """
  258. if "id" in session:
  259. self._debug("Logging out session id=%d", session["id"])
  260. self._invalidate_session()