コード例 #1
0
ファイル: utils.py プロジェクト: tai-hatake/fastapi-mysql
def send_email(
    email_to: str,
    subject_template: str = "",
    html_template: str = "",
    environment: Dict[str, Any] = {},
) -> None:
    assert get_settings(
    ).EMAILS_ENABLED, "no provided configuration for email variables"
    message = emails.Message(
        subject=JinjaTemplate(subject_template),
        html=JinjaTemplate(html_template),
        mail_from=(get_settings().EMAILS_FROM_NAME,
                   get_settings().EMAILS_FROM_EMAIL),
    )
    smtp_options = {
        "host": get_settings().SMTP_HOST,
        "port": get_settings().SMTP_PORT
    }
    if get_settings().SMTP_TLS:
        smtp_options["tls"] = True
    if get_settings().SMTP_USER:
        smtp_options["user"] = get_settings().SMTP_USER
    if get_settings().SMTP_PASSWORD:
        smtp_options["password"] = get_settings().SMTP_PASSWORD
    login_email_server()
    response = message.send(to=email_to, render=environment, smtp=smtp_options)
    logging.info(f"send email result: {response}")
コード例 #2
0
ファイル: security.py プロジェクト: tai-hatake/fastapi-mysql
def create_access_token(subject: Union[str, Any],
                        expires_delta: timedelta = None) -> str:
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(
            minutes=get_settings().ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode = {"exp": expire, "sub": str(subject)}
    encoded_jwt = jwt.encode(to_encode,
                             get_settings().SECRET_KEY,
                             algorithm=ALGORITHM)
    return encoded_jwt
コード例 #3
0
ファイル: utils.py プロジェクト: tai-hatake/fastapi-mysql
def send_test_email(email_to: str) -> None:
    project_name = get_settings().PROJECT_NAME
    subject = f"{project_name} - Test email"
    with open(Path(get_settings().EMAIL_TEMPLATES_DIR) /
              "test_email.html") as f:
        template_str = f.read()
    send_email(
        email_to=email_to,
        subject_template=subject,
        html_template=template_str,
        environment={
            "project_name": get_settings().PROJECT_NAME,
            "email": email_to
        },
    )
コード例 #4
0
ファイル: utils.py プロジェクト: tai-hatake/fastapi-mysql
def send_new_account_email(email_to: str, username: str,
                           password: str) -> None:
    project_name = get_settings().PROJECT_NAME
    subject = f"{project_name} - New account for user {username}"
    with open(
            Path(settget_settings().EMAIL_TEMPLATES_DIR) /
            "new_account.html") as f:
        template_str = f.read()
    link = get_settings().SERVER_HOST
    send_email(
        email_to=email_to,
        subject_template=subject,
        html_template=template_str,
        environment={
            "project_name": get_settings().PROJECT_NAME,
            "username": username,
            "password": password,
            "email": email_to,
            "link": link,
        },
    )
コード例 #5
0
ファイル: utils.py プロジェクト: tai-hatake/fastapi-mysql
def send_reset_password_email(email_to: str, email: str, token: str) -> None:
    project_name = get_settings().PROJECT_NAME
    subject = f"{project_name} - Password recovery for user {email}"
    with open(
            Path(get_settings().EMAIL_TEMPLATES_DIR) /
            "reset_password.html") as f:
        template_str = f.read()
    server_host = get_settings().SERVER_HOST
    link = f"{server_host}/reset-password?token={token}"
    send_email(
        email_to=email_to,
        subject_template=subject,
        html_template=template_str,
        environment={
            "project_name": get_settings().PROJECT_NAME,
            "username": email,
            "email": email_to,
            "valid_hours": get_settings().EMAIL_RESET_TOKEN_EXPIRE_HOURS,
            "link": link,
        },
    )
コード例 #6
0
ファイル: common.py プロジェクト: tai-hatake/fastapi-mysql
def get_current_user(db: Session = Depends(get_db),
                     token: str = Depends(reusable_oauth2)) -> models.User:
    try:
        payload = jwt.decode(token,
                             get_settings().SECRET_KEY,
                             algorithms=[ALGORITHM])
        token_data = schemas.TokenPayload(**payload)
    except (jwt.JWTError, ValidationError):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Could not validate credentials",
        )
    user = logics.user.get(db, id=token_data.sub)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user
コード例 #7
0
ファイル: helpers.py プロジェクト: VeroCity-UG/CarbonFutures
import jwt
from datetime import datetime, timedelta
from api.config import get_settings
from .schemas import User
from fastapi import Header, HTTPException, status
from fastapi.security.utils import get_authorization_scheme_param
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.params import Security
from pydantic import ValidationError

settings = get_settings()
security = HTTPBearer()
credentials_exception = HTTPException(
    status_code=status.HTTP_401_UNAUTHORIZED,
    detail="Could not validate credentials",
    headers={"WWW-Authenticate": "Bearer"},
)


def row2dict(row):
    d = {}
    for column in row.__table__.columns:
        d[column.name] = str(getattr(row, column.name))

    return d


def get_user_from_header(credentials: HTTPAuthorizationCredentials = Security(
    security)) -> User:
    try:
        payload = jwt.decode(credentials.credentials,
コード例 #8
0
from typing import Generator
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from api.config import get_settings

user_name = get_settings().MYSQL_USER
password = get_settings().MYSQL_PASSWORD
host = get_settings().DOCKER_DB_HOST
database_name = get_settings().MYSQL_DATABASE

DATABASE = 'mysql://%s:%s@%s/%s?charset=utf8' % (
    user_name,
    password,
    host,
    database_name,
)

engine = create_engine(DATABASE,
                       pool_pre_ping=True,
                       encoding='utf-8',
                       echo=True)
sessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
コード例 #9
0
ファイル: utils.py プロジェクト: tai-hatake/fastapi-mysql
def login_email_server():
    server = smtplib.SMTP_SSL(get_settings().SMTP_HOST,
                              get_settings().SMTP_PORT,
                              context=ssl.create_default_context())
    server.login(get_settings().SMTP_USER, get_settings().SMTP_PASSWORD)