def create_token(user, aid=None, ttl=None):
    """
    Create a valid JWT for a given user/api key, this token is then used to authenticate
    sessions until the token expires.

    :param user:
    :return:
    """
    expiration_delta = timedelta(days=1)
    custom_expiry = current_app.config.get("LEMUR_TOKEN_EXPIRATION")
    if custom_expiry:
        if isinstance(custom_expiry, str) and custom_expiry.endswith("m"):
            expiration_delta = timedelta(
                minutes=int(custom_expiry.rstrip("m"))
            )
        elif isinstance(custom_expiry, str) and custom_expiry.endswith("h"):
            expiration_delta = timedelta(
                hours=int(custom_expiry.rstrip("h"))
            )
        else:
            expiration_delta = timedelta(
                days=int(custom_expiry)
            )
    payload = {"iat": datetime.utcnow(), "exp": datetime.utcnow() + expiration_delta}

    # Handle Just a User ID & User Object.
    if isinstance(user, int):
        payload["sub"] = str(user)
    else:
        payload["sub"] = str(user.id)
    if aid is not None:
        payload["aid"] = aid
    # Custom TTLs are only supported on Access Keys.
    if ttl is not None and aid is not None:
        # Tokens that are forever until revoked.
        if ttl == -1:
            del payload["exp"]
        else:
            payload["exp"] = datetime.utcnow() + timedelta(days=ttl)
    token_secrets = current_app.config.get("LEMUR_TOKEN_SECRETS", [current_app.config["LEMUR_TOKEN_SECRET"]])
    token = jwt.encode(payload, token_secrets[0])
    return token

    Create a valid JWT for a given user/api key, this token is then used to authenticate
    sessions until the token expires.

    :param user:
    :return:
    
lemur/auth/service.py