🐛 fix(api_key.py): add hashed_api_key field to ApiKey model to store hashed version of api_key
🐛 fix(crud.py): update create_api_key function to use hashed version of generated_api_key and mask the api_key for security reasons
This commit is contained in:
parent
927379b245
commit
a31d1f104d
2 changed files with 11 additions and 6 deletions
|
|
@ -17,7 +17,9 @@ class ApiKeyBase(SQLModelSerializable):
|
|||
|
||||
class ApiKey(ApiKeyBase, table=True):
|
||||
id: UUID = Field(default_factory=uuid4, primary_key=True, unique=True)
|
||||
|
||||
api_key: str = Field(index=True, unique=True)
|
||||
hashed_api_key: str = Field(index=True)
|
||||
# User relationship
|
||||
user_id: UUID = Field(index=True, foreign_key="user.id")
|
||||
user: "User" = Relationship(back_populates="api_keys")
|
||||
|
|
|
|||
|
|
@ -24,17 +24,20 @@ def create_api_key(
|
|||
generated_api_key = secrets.token_urlsafe(32)
|
||||
|
||||
# hash the API key
|
||||
hashed_api_key = get_password_hash(generated_api_key)
|
||||
hashed = get_password_hash(generated_api_key)
|
||||
# Use the generated key to create the ApiKey object
|
||||
|
||||
api_key = ApiKey(api_key=hashed_api_key, name=api_key_create.name, user_id=user_id)
|
||||
masked_api_key = f"{'*' * 10}{generated_api_key[-4:]}"
|
||||
api_key = ApiKey(
|
||||
api_key=masked_api_key,
|
||||
hashed_api_key=hashed,
|
||||
name=api_key_create.name,
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
session.add(api_key)
|
||||
session.commit()
|
||||
session.refresh(api_key)
|
||||
unmasked = UnmaskedApiKeyRead.from_orm(api_key)
|
||||
unmasked.api_key = generated_api_key
|
||||
return unmasked
|
||||
return UnmaskedApiKeyRead.from_orm(api_key)
|
||||
|
||||
|
||||
def delete_api_key(session: Session, api_key_id: UUID) -> None:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue