2023-10-15 16:17:37 +02:00
|
|
|
from fastapi import APIRouter, HTTPException, status
|
|
|
|
from ..dependencies import users_token, database, mail
|
|
|
|
from ..models import users, email
|
|
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from fastapi_mail import MessageSchema, MessageType, FastMail
|
|
|
|
import random
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
|
|
|
|
|
|
@router.post("/mail",tags=["mail"])
|
|
|
|
async def read_users_me(userSingle: users.UserCreate | None = None):
|
|
|
|
if userSingle is None:
|
|
|
|
raise HTTPException(
|
|
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
|
|
detail="Body request is empty"
|
|
|
|
)
|
|
|
|
user_repository = users.UserRepository(database=database.database)
|
2023-10-15 16:26:20 +02:00
|
|
|
user = user_repository.find_one_by({"$or": [{"username": {'$eq': userSingle.username}},{"email": {"$eq": userSingle.email}}] })
|
2023-10-15 16:17:37 +02:00
|
|
|
if user is not None:
|
|
|
|
raise HTTPException(
|
|
|
|
status_code=status.HTTP_204_NO_CONTENT,
|
|
|
|
detail="User is already exist"
|
|
|
|
)
|
|
|
|
|
|
|
|
fm = FastMail(mail.conf)
|
|
|
|
numberkey = str(random.Random())
|
|
|
|
key_hashed = users_token.get_password_hash(numberkey)
|
|
|
|
email_body = {"key":key_hashed, "username":userSingle.username}
|
|
|
|
email_schema = email.EmailSchema(email=[userSingle.email], body=email_body)
|
|
|
|
message = MessageSchema(
|
|
|
|
subject="Fastapi-Mail module",
|
|
|
|
recipients=email_schema.dict().get("email"),
|
|
|
|
template_body=email_schema.dict().get("body"),
|
|
|
|
subtype=MessageType.html,
|
|
|
|
)
|
|
|
|
|
|
|
|
await fm.send_message(message, template_name="mailer.html")
|
|
|
|
current_user = users.User(username=userSingle.username, password=users_token.get_password_hash(userSingle.password), email=userSingle.email)
|
|
|
|
user_repository.save(current_user)
|
|
|
|
return JSONResponse(status_code=200, content={"message": "email has been sent"})
|