Metadata-Version: 2.3
Name: oidc-python
Version: 0.1.0
Summary: This project developed for intagration OICD in your project
Requires-Dist: httpx>=0.28.1
Requires-Dist: logly>=0.1.6
Requires-Dist: pytest>=9.0.1
Requires-Dist: pytest-asyncio>=1.3.0
Requires-Dist: python-jose[cryptography]>=3.5.0
Requires-Python: >=3.13
Description-Content-Type: text/markdown

# OICD


# oidc

> version: 0.1.0

This package is designed for use in your application with OIDC.

## Features

- feature 

## Install

pip install oidc

## Use examples

#### API для OICD на библиотеки Sanic

Как пользоваться библиотекой OICD :
Изначально нам необходим редирект на Keycloak

Например, в Sanic мы создаем объект:
Передаем url БД redis и имя Realm

``` python
app.ctx.oidc_client = CreateOIDCClient(config["REDIS_URL"],
                           config['KEYCLOAK_REALM_NAME'])
```

Теперь получаем редирект передаем конфиг: config:dict там переменные
окружения передаем с .env

```python
app.ctx.redirect_uri = app.ctx.oidc_client.get_redirect_uri(config)

```
Пример:
```Python

# Открываем соединение с Redis при старте
@api.before_server_start
async def setup_redis(app, _):
    # Подключаем Redis
    app.ctx.redis = redis.from_url(
        config["REDIS_URL"],
        decode_responses=True
    )

    # Создаём OIDC + PKCE менеджеры на основе redis URL
    createOIDCClient = CreateOIDCClient(config, app.ctx.redis)
    app.ctx.oidc_client = createOIDCClient

# например на маршрут /login
@api.get("/login")
async def auth_login(request):
    return response.redirect(request.app.ctx.redirect_uri)

```


Нас перебрасывает на сервис Keycloak

Авторизируемся

После успешной авторизации мы пропускаем в наше приложение:

```python
@api.get("/callback")
async def auth_callback(request: Request):
    # Достаем код и state
    
    code = request.args.get("code")
    state = request.args.get("state")

    if not code or not state:
        return response.json({"error": "Missing code or state"}, status=400)

    code_verifier = await request.app.ctx.oidc_client.pkce.pop(state)
    
    if not code_verifier:
        return response.json({"error": "Invalid/expired state"}, status=400)

    try:
        tokens = await request.app.ctx.oidc_client.exchange_code(code, code_verifier)
    except Exception as e:
        return response.json(
            {"error": "Token exchange failed", "details": str(e)},
            status=400
        )

    claims = await request.app.ctx.oidc_client.oidc.verify_token(tokens["access_token"])

    await request.app.ctx.oidc_client.save_session(claims["sub"], tokens, claims)

    return response.json({"message": "ok", "user": claims})
```


Для проверки токена и пользователя, мы используем middleware 

Пример:

```python
@api.middleware("request")
async def keycloak_middleware(request: Request):
    auth = request.headers.get("Authorization")
    if not auth:
        request.ctx.user = None
        logger.info(f"User is : {request.ctx.user}")
        return

    token = auth.replace("Bearer ", "")
    request.ctx.user = await (request.app.ctx.oidc_client.get_user_from_token(token))
    
```



## Roadmap

 - [ ] 0.1.0 init

## Develop 

### install

how to install for develop

### structure modules

### add feature

### publish
