Module sanic_security.utils

Functions

def get_code(digits_only: bool = False) ‑> str
Expand source code
def get_code(digits_only: bool = False) -> str:
    """
    Generates random code to be used for verification.

    Args:
        digits_only: Determines if code should only contain digits.

    Returns:
        code
    """
    return "".join(
        secrets.choice(("" if digits_only else ascii_uppercase) + digits)
        for _ in range(6)
    )

Generates random code to be used for verification.

Args

digits_only
Determines if code should only contain digits.

Returns

code

def get_expiration_date(seconds: int) ‑> datetime.datetime
Expand source code
def get_expiration_date(seconds: int) -> datetime.datetime:
    """
    Retrieves the date after which something (such as a session) is no longer valid.

    Args:
        seconds: Seconds added to current time.

    Returns:
        expiration_date
    """
    return (
        datetime.datetime.now(datetime.UTC) + datetime.timedelta(seconds=seconds)
        if seconds > 0
        else None
    )

Retrieves the date after which something (such as a session) is no longer valid.

Args

seconds
Seconds added to current time.

Returns

expiration_date

def get_ip(request: sanic.request.types.Request) ‑> str
Expand source code
def get_ip(request: Request) -> str:
    """
    Retrieves ip address from client request.

    Args:
        request (Request): Sanic request parameter.

    Returns:
        ip
    """
    return request.remote_addr or request.ip

Retrieves ip address from client request.

Args

request : Request
Sanic request parameter.

Returns

ip

def is_expired(date)
Expand source code
def is_expired(date):
    """
    Checks if current date has surpassed the date passed into the function.

    Args:
        date: The date being checked for expiration.

    Returns:
        is_expired
    """
    return date and datetime.datetime.now(datetime.timezone.utc) >= date

Checks if current date has surpassed the date passed into the function.

Args

date
The date being checked for expiration.

Returns

is_expired

def json(message: str, data, status_code: int = 200) ‑> sanic.response.types.HTTPResponse
Expand source code
def json(message: str, data, status_code: int = 200) -> HTTPResponse:
    """
    A preformatted Sanic json response.

    Args:
        message (str): Message describing data or relaying human-readable information.
        data (Any): Raw information to be used by client.
        status_code (int): HTTP response code.

    Returns:
        json
    """
    return sanic_json(
        {"message": message, "code": status_code, "data": data}, status=status_code
    )

A preformatted Sanic json response.

Args

message : str
Message describing data or relaying human-readable information.
data : Any
Raw information to be used by client.
status_code : int
HTTP response code.

Returns

json

async def send_email(to_address, subject, data)
Expand source code
async def send_email(to_address, subject, data):
    """
    Sends an email to a given address. Renders an HTML template from config.TEMPLATE_PATH if it exists, substituting
    values from data. Otherwise, raw text will be sent.

    Args:
        to_address (str): Recipient's email address.
        subject (str): Subject line of the email.
        data (dict | str): Substitution values for the template if one exists, otherwise the plain text body.
    """
    msg = MIMEMultipart()
    msg["From"] = config.SMTP_FROM
    msg["To"] = to_address
    msg["Subject"] = subject
    if os.path.exists(config.TEMPLATE_PATH):
        with open(config.TEMPLATE_PATH, "r", encoding="utf-8") as f:
            html_content = Template(f.read()).safe_substitute(data)
        msg.attach(MIMEText(html_content, "html"))
    else:
        msg.attach(MIMEText(data, "plain"))
    await aiosmtplib.send(
        msg,
        hostname=config.SMTP_HOSTNAME,
        port=config.SMTP_PORT,
        start_tls=config.SMTP_START_TLS,
        username=config.SMTP_USERNAME,
        password=config.SMTP_PASSWORD,
    )

Sends an email to a given address. Renders an HTML template from config.TEMPLATE_PATH if it exists, substituting values from data. Otherwise, raw text will be sent.

Args

to_address : str
Recipient's email address.
subject : str
Subject line of the email.
data : dict | str
Substitution values for the template if one exists, otherwise the plain text body.
def str_to_bool(val: str) ‑> bool
Expand source code
def str_to_bool(val: str) -> bool:
    """Returns false if val is None instead of raising ValueError (Sanic's implementation)."""
    return sanic_str_to_bool(val) if val else False

Returns false if val is None instead of raising ValueError (Sanic's implementation).