/ src / python / txtai / api / authorization.py
authorization.py
 1  """
 2  Authorization module
 3  """
 4  
 5  import hashlib
 6  import os
 7  
 8  from fastapi import Header, HTTPException
 9  
10  
11  class Authorization:
12      """
13      Basic token authorization.
14      """
15  
16      def __init__(self, token=None):
17          """
18          Creates a new Authorization instance.
19  
20          Args:
21              token: SHA-256 hash of token to check
22          """
23  
24          self.token = token if token else os.environ.get("TOKEN")
25  
26      def __call__(self, authorization: str = Header(default=None)):
27          """
28          Validates authorization header is present and equal to current token.
29  
30          Args:
31              authorization: authorization header
32          """
33  
34          if not authorization or self.token != self.digest(authorization):
35              raise HTTPException(status_code=401, detail="Invalid Authorization Token")
36  
37      def digest(self, authorization):
38          """
39          Computes a SHA-256 hash for input authorization token.
40  
41          Args:
42              authorization: authorization header
43  
44          Returns:
45              SHA-256 hash of authorization token
46          """
47  
48          # Replace Bearer prefix
49          prefix = "Bearer "
50          token = authorization[len(prefix) :] if authorization.startswith(prefix) else authorization
51  
52          # Compute SHA-256 hash
53          return hashlib.sha256(token.encode("utf-8")).hexdigest()