MCPcopy Create free account
hub / github.com/dbunt1tled/python-fast-api / HashService

Class HashService

src/core/service/hash_service.py:16–153  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

14
15
16class HashService:
17 def __init__(self, cfg: Settings) -> None:
18 self.cfg = cfg
19 self.jwt_public_key = base64.b64decode(cfg.jwt_public_key).decode("utf-8")
20 self.jwt_private_key = base64.b64decode(cfg.jwt_private_key).decode("utf-8")
21 self.jwt_algorithm = cfg.jwt_algorithm
22 if self.jwt_algorithm is None or self.jwt_algorithm == "":
23 self.jwt_algorithm = "RS256"
24 self.hasher = PasswordHasher()
25
26 def verify_x_api_key(self, key: str) -> bool:
27 return self.verify_hash(key, self.cfg.x_api_key)
28
29 @staticmethod
30 def verify_hash(hash1: str, hash2: str) -> bool:
31 return secrets.compare_digest(hash1, hash2)
32
33 @staticmethod
34 def uuid4() -> uuid.UUID:
35 return uuid.uuid4()
36
37 def hash_password(self, password: str) -> str:
38 return self.hasher.hash(password)
39
40 def verify_password(self, password: str, hashed_password: str) -> bool:
41 try:
42 self.hasher.verify(hashed_password, password)
43 return True
44 except VerifyMismatchError:
45 return False
46
47 def create_access_token(self, user: User) -> Token:
48 exp = datetime.now() + timedelta(hours=self.cfg.jwt_access_token_exp_h)
49 payload = {
50 "sub": str(user.id),
51 "type": TokenType.ACCESS,
52 "session": user.session,
53 "exp": int(exp.timestamp()),
54 }
55
56 token = jwt.encode(payload, self.jwt_private_key, algorithm=self.jwt_algorithm)
57
58 return Token(
59 subject=str(user.id),
60 token=str(token),
61 token_type=TokenType.ACCESS,
62 expires_in=exp,
63 )
64
65 def create_refresh_token(self, user: User) -> Token:
66 exp = datetime.now() + timedelta(hours=self.cfg.jwt_refresh_token_exp_h)
67 payload = {
68 "sub": str(user.id),
69 "type": TokenType.REFRESH,
70 "session": user.session,
71 "exp": int(exp.timestamp()),
72 }
73

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected