Реализация avito-trainee-task
HTTP сервис для одноразовых секретов наподобие https://onetimesecret.com/.
Он должен позволить создать секрет, задать кодовую фразу для его открытия и cгенерировать код, по которому можно прочитать секрет только один раз. UI не нужен, это должен быть JSON Api сервис.
Для написание сервиса можно использовать FastAPI или любой другой фреймворк.
Метод /generate должен принимать секрет и кодовую фразу и отдавать secret_key по которому этот секрет можно получить.
Метод /secrets/{secret_key} принимает на вход кодовую фразу и отдает секрет.
Запуск: uvicorn main:app --host 0.0.0.0
This is a code implementation that utilizes the FastAPI framework to create an API for generating and retrieving secrets. The secrets are stored in a MongoDB database using the motor
library for asynchronous database operations.
- secrets
- fastapi
- pydantic
- motor (motor.motor_asyncio.AsyncIOMotorClient)
secrets
is imported to generate secure and random secret keys.FastAPI
is imported from thefastapi
module which is used to build the API.BaseModel
is imported frompydantic
to define the structure of the secret data.AsyncIOMotorClient
is imported frommotor.motor_asyncio
to establish a connection with the MongoDB database.
- An instance of the
FastAPI
class is created and assigned to theapp
variable.
- The
Secret
class is defined as a PydanticBaseModel
with two fields:secret
andpassphrase
.
- The
Database
class is defined to handle database operations. - The class constructor takes a MongoDB connection URL and initializes the database connection using
AsyncIOMotorClient
. - The
save_secret
method asynchronously saves a secret to the database.- It generates a unique secret key using
secrets.token_hex
. - Inserts the secret data into the
secrets
collection with the generated secret key as the document ID. - Returns the secret key.
- It generates a unique secret key using
- The
get_secret
method asynchronously retrieves a secret from the database using the provided secret key and passphrase.- It searches for the document with the given secret key.
- If the document exists, it checks if the provided passphrase matches the stored passphrase.
- If the passphrase matches, it deletes the document from the database and returns the secret.
- If the secret key or passphrase is invalid, it raises an
HTTPException
with status code 404.
- An instance of the
Database
class is created with the MongoDB connection URL "mongodb://localhost:27017" and assigned to thedb
variable.
-
@app.post("/generate")
defines a POST endpoint where clients can generate a new secret.- It expects a JSON payload with the structure defined by the
Secret
model. - Calls the
save_secret
method to save the secret to the database and retrieves the generated secret key. - Returns a JSON response containing the generated secret key.
- It expects a JSON payload with the structure defined by the
-
@app.get("/secrets/{secret_key}")
defines a GET endpoint for retrieving a secret.- It expects the
secret_key
andpassphrase
as path parameters. - Calls the
get_secret
method to retrieve the secret from the database. - Returns a JSON response containing the retrieved secret.
- It expects the
-
To generate a new secret:
- HTTP Method: POST
- Endpoint: /generate
- Request Body:
or
{ "secret": "my_secret", "passphrase": "my_passphrase" }
{ "secret": "another_secret", "passphrase": "another_passphrase" }
- Response:
{ "secret_key": "7c20a8cbe33d78142d4e670665165b19" }
-
To retrieve a secret:
- HTTP Method: GET
- Endpoint: /secrets/{secret_key}
- Path Parameters:
- secret_key: The secret key returned from the generate endpoint.
- passphrase: The passphrase used when generating the secret.
- Response:
{ "secret": "my_secret" }
Note: If the secret key or passphrase is invalid, an HTTP 404 response will be returned with the error message "Secret not found".