Metadata-Version: 2.1
Name: auth_lib_profcomff
Version: 2024.6.22
Summary: Библиотека функций авторизации для микросервисов Твой ФФ!
Author-email: "profcomff.com" <admin@profcomff.com>, Semyon Grigoriev <grigoriev@profcomff.com>, Roman Dyakov <roman@dyakov.space>
License: BSD 3-Clause License
        
        Copyright (c) 2022, Профком студентов физфака МГУ
        All rights reserved.
        
        Redistribution and use in source and binary forms, with or without
        modification, are permitted provided that the following conditions are met:
        
        1. Redistributions of source code must retain the above copyright notice, this
           list of conditions and the following disclaimer.
        
        2. Redistributions in binary form must reproduce the above copyright notice,
           this list of conditions and the following disclaimer in the documentation
           and/or other materials provided with the distribution.
        
        3. Neither the name of the copyright holder nor the names of its
           contributors may be used to endorse or promote products derived from
           this software without specific prior written permission.
        
        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
        AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
        FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
        DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
        SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
        CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
        OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        
Project-URL: Homepage, https://app.profcomff.com
Project-URL: Documentation, https://github.com/profcomff/auth-lib/blob/main/README.md
Project-URL: Repository, https://github.com/profcomff/auth-lib
Project-URL: Issues, https://github.com/profcomff/auth-lib/issues
Project-URL: Changelog, https://github.com/profcomff/auth-lib/releases
Classifier: Development Status :: 5 - Production/Stable
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests
Provides-Extra: aio
Requires-Dist: aiohttp ; extra == 'aio'
Provides-Extra: airflow
Requires-Dist: flask ; extra == 'airflow'
Requires-Dist: apache-airflow ; extra == 'airflow'
Provides-Extra: fastapi
Requires-Dist: fastapi ; extra == 'fastapi'
Requires-Dist: starlette ; extra == 'fastapi'
Requires-Dist: pydantic ; extra == 'fastapi'
Requires-Dist: pydantic-settings ; extra == 'fastapi'
Provides-Extra: style
Requires-Dist: black ; extra == 'style'
Requires-Dist: isort ; extra == 'style'
Requires-Dist: pydocstyle ; extra == 'style'
Requires-Dist: autoflake ; extra == 'style'
Provides-Extra: testing
Requires-Dist: pytest ; extra == 'testing'
Requires-Dist: pytest-cov ; extra == 'testing'
Requires-Dist: pytest-mock ; extra == 'testing'
Requires-Dist: httpx ; extra == 'testing'
Requires-Dist: requests ; extra == 'testing'

# auth-lib
Библиотека функций авторизации для микросервисов Твой ФФ!

[![pypi](https://img.shields.io/pypi/dm/auth-lib-profcomff?label=PIP%20INSTALLS&style=for-the-badge)](https://pypi.org/project/auth-lib-profcomff)
[![tg](https://img.shields.io/badge/telegram-Viribus%20unitis-brightgreen?style=for-the-badge&logo=telegram)](https://t.me/+eIMtCymYDepmN2Ey)


## Функционал
Хранение общих методов аутентификации и авторизации для бэкендов Твой ФФ

## Примеры использования
### FastAPI
```python
from auth_lib.fastapi import UnionAuth
from fastapi import APIRouter, Depends
router = APIRouter(prefix="/...")

## Чтобы дернуть ручку нужен один скоуп, авторизация обязательна
## Юзкейс https://github.com/profcomff/timetable-api/blob/a374c74cd960941100f6c923ff9c3ff706a1ed09/calendar_backend/routes/room/room.py#L45
@router.smth("/")
async def foo(_=Depends(UnionAuth(scopes=["service.resource.method"], allow_none=False, auto_error=True))):
  pass

## Чтобы дернуть ручку нужно два скоупа, авторизация обязательна
## Юзкейс https://github.com/profcomff/print-api/blob/775f36fdd185eec8d9096d3472b7730cf5ac9798/print_service/routes/user.py#L78
@router.smth("/")
async def bar(_=Depends(UnionAuth(scopes=["scope1", "scope2"], allow_none=False, auto_error=True))):
  pass

## Чтобы дернуть ручку не нужны скоупы, авторизация необязательна, но если передана недействительная сессия, то кинет ошибку
@router.smth("/")
async def baz(_=Depends(UnionAuth(scopes=[], allow_none=True, auto_error=True))):
  pass


## Чтобы дернуть ручку не нужны скоупы, авторизация обязательна
@router.smth("/")
async def foo(_=Depends(UnionAuth(scopes=[], allow_none=False, auto_error=True))):
  pass

```
Depends вызывает инстанс класса с нужными параметрами и возвращает словарь со всеми полями отсюда https://api.test.profcomff.com/#/Logout/me_me_get

#### Параметры конструктора UnionAuth
- `scopes: list[str]` - список имен скоупов, которые нужны в данной ручке. Например `["printer.user.create", "printer.user.delete"]`
- `allow_none: bool` - Если true, то при отсутствии нужного заголовка в запросе ручка будет доступна юзеру, если заголовк передан, то обработка идет в зависимости от следующего параметра
- `auto_error: bool` - если `True`, то при несовпадении скоупов/завершенной сессии и т.д. (на запрос `GET /me` не 200) - кинет 401, если `False`, то не будет кидать ошибки, но будет возвращать `None`

Чтобы задать хост авторизации надо в переменные окружения или в .env файл прописать AUTH_URL="..."

#### Настройки
```python
auth_url="https://api.test.profcomff.com/auth/"
AUTH_AUTO_ERROR: bool = True
AUTH_ALLOW_NONE: bool = False

```

## Тестирование сервисов
Установите нужные завивсимости
```shell
pip install 'auth-lib-profcomff[testing]'
```

Используйте маркировку для тестирования
```python
import pytest
from fastapi.testclient import TestClient
from fastapi import FastAPI

@pytest.fixture
def client(auth_mock):
    yield TestClient(FastAPI())

@pytest.mark.authenticated("scope1", "scope2", ..., user_id=5)
def test1(client):
    """
    В этом тесте будут выданы скоупы scope1, scope2, user_id в ответе будет равен 5
    библиотека не будет проверять токен через АПИ, будет просто возвращать
    нужный словарь, как будто пользователь авторизован с нужными скоупами
    """
    assert 2*2 == 4


@pytest.mark.authenticated()
def test2(client):
    """
    В этом тесте скоупов выдано не будет, user_id будет равен 0
    но библиотека не будет проверять токен через АПИ, будет просто возвращать
    нужный словарь, как будто пользователь авторизован с нужными скоупами
    """
    assert 2*2 == 4


def test3(client):
    """
    В этом тесте скоупов выдано не будет, библиотека будет проверять
    токен через АПИ
    """
    assert 2*2 == 4
```

## Contributing 
 - Основная [информация](https://github.com/profcomff/.github/wiki/%255Bdev%255D-Backend-%25D1%2580%25D0%25B0%25D0%25B7%25D1%2580%25D0%25B0%25D0%25B1%25D0%25BE%25D1%2582%25D0%25BA%25D0%25B0) по разработке наших приложений

 - [Ссылка](https://github.com/profcomff/auth-lib/blob/main/CONTRIBUTING.md) на страницу с информацией по разработке auth-lib
