Metadata-Version: 2.4
Name: drf-authentication-quick
Version: 0.1.1
Summary: Django REST Framework authentication package with JWT, MFA, email verification, password reset, OAuth login, and secure cookie-token support.
Author-email: Ubaid <ubaidullah.developer2@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/codewithubaid1/drf-auth
Project-URL: Repository, https://github.com/codewithubaid1/drf-auth
Project-URL: Documentation, https://github.com/codewithubaid1/drf-auth#readme
Keywords: django,django-rest-framework,drf,jwt,oauth,social-auth,authentication,authorization,mfa,email-verification,password-reset,cookie-authentication,drf-auth
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: Django
Classifier: Framework :: Django :: 4.2
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: Django>=4.2
Requires-Dist: djangorestframework>=3.14
Requires-Dist: djangorestframework-simplejwt>=5.3
Requires-Dist: requests==2.34.2
Dynamic: license-file

# drf-authentication-quick

`drf-authentication-quick` is a Django REST Framework authentication package that gives you a ready-to-use authentication flow with:

- JWT access and refresh tokens
- email verification during registration
- MFA verification with one-time password delivery
- password reset flow
- cookie-based token transport support
- OAuth login for Google, GitHub, and Facebook
- reusable email templates for registration, MFA, and password reset

This README explains how to install the package, configure it in your Django project, and understand every supported setting in `AUTH_SETTINGS`.

## Installation

Install the package from PyPI:

```bash
pip install drf-authentication-quick
```


## Step 1: Add the app to Django

In your Django project settings, add the app to `INSTALLED_APPS`:

```python
INSTALLED_APPS = [
    # your existing apps
    "rest_framework",
    "drf_auth",
]
```

You should also have Django REST Framework installed and configured in your project.



## Step 2: Add the app to Django

After including the app in INSTALLED_APPS you should make migrations and migrate:

```python
   python manage.py makemigrations drf_auth
   python manage.py migrate
```

It will add tables, sessions and token sessions required for authentication.

## Step 3: Configure the authentication package

Create a dictionary named `AUTH_SETTINGS` in your Django settings and pass the options you want to enable.

A simple example:

```python
AUTH_SETTINGS = {
    "EMAIL_VERIFICATION": True,
    "PASSWORD_RESET": True,
    "MFA_ENABLED": True,
    "MFA_METHOD": "email",
    "RESTRICT_MULTIPLE_LOGINS": False,

    "ACCESS_COOKIE_NAME": "access_token",
    "REFRESH_COOKIE_NAME": "refresh_token",
    "COOKIE_SECURE": False,
    "COOKIE_HTTP_ONLY": True,
    "COOKIE_SAMESITE": "Lax",
    "ACCESS_COOKIE_PATH": "/",
    "REFRESH_COOKIE_PATH": "/",
    "COOKIE_DOMAIN": None,
    "AUTH_TRANSPORT_HEADER": "X-Auth-Transport",
    "ACCESS_COOKIE_MAX_AGE": 60 * 15,
    "REFRESH_COOKIE_MAX_AGE": 60 * 60 * 24 * 7,

    "PASSWORD_RESET_EXPIRY": 60 * 30,
    "PASSWORD_RESET_URL": "http://localhost:3000/reset-password",

    "OAUTH_ENABLED": False,
    "OAUTH_PROVIDERS": {},
    "STORE_PROVIDER_TOKENS": False,
    "SYNC_OAUTH_AVATAR": True,
}
```

## Step 4: Configure Url Patterns

Add the package url to your project urls.py.
A simple example:

```python
   from django.urls import path, include

   urlpatterns = [
        ...
        path("accounts/", include("drf_auth.urls"))
   ]
```

If you don't set the urls the package will not work.

## Step 5: Required Django settings outside `AUTH_SETTINGS`

Besides `AUTH_SETTINGS`, the package also reads some values directly from your Django project settings module.

These are not part of `AUTH_SETTINGS`, so you should define them in your project's normal settings file:

```python
BACKEND_URL = "http://localhost:8000"
CLIENT_URL = "http://localhost:3000/"
SITE_NAME = "My Project"
URL_PATTERN_NAME = "accounts"
```

### What each one is used for

- `BACKEND_URL` — base backend URL used when building verification and password reset links in emails.
  If it is not set, the package falls back to `http://localhost:8000`.
- `CLIENT_URL` — frontend base URL used when redirecting the user after email verification or password reset token validation.
  If it is not set, the package falls back to `http://localhost:3000/`.
- `SITE_NAME` — display name used inside email templates.
  If it is not set, the package falls back to `DRF Project`.
- `URL_PATTERN_NAME` — the URL prefix name used when building the email verification and password reset links.
  If it is not set, the package falls back to `accounts`.

> In short: if you want the links and redirects to point to your real app URLs, define these settings yourself. Otherwise the package will still run, but it will use the built-in local defaults shown above.

## Step 6: Make sure your custom user model works with the package

This package expects a Django user model with the usual email/username/password fields and the internal token tracking behavior used by the package.

Make sure your project has a custom user model if required by your application, and that it supports:

- `username`
- `email`
- `password`
- `is_verified`
- `token_version`
- `auth_token`

The package also creates and uses model tables for MFA sessions, password reset sessions, and OAuth accounts.

## How the auth flow works

### 1. Register a user

Send a `POST` request to:

```http
POST /register/
```

Expected payload:

```json
{
  "username": "jane",
  "email": "jane@example.com",
  "password": "secret123"
}
```

If `EMAIL_VERIFICATION` is enabled, the user is created and a verification email is sent. The account is not fully usable until the user confirms the email link.

### 2. Verify email

When `EMAIL_VERIFICATION` is enabled, the registration response asks the user to verify the email address.

The package builds a verification URL using:

- `BACKEND_URL` from Django settings, or fallback `http://localhost:8000`
- `URL_PATTERN_NAME` from Django settings, or fallback `accounts`

The verification endpoint is:

```http
GET /verify/email/<uuid:token>/
```

The user is redirected to your frontend login page with a success or error message in the query string.

### 3. Login

Send a `POST` request to:

```http
POST /login/
```

Payload:

```json
{
  "username": "jane",
  "password": "secret123"
}
```

How the login response is shaped depends on the transport:

- Header transport: returns JWT tokens in the JSON response.
- Cookie transport: sets cookie-based access and refresh tokens and returns a simple success message.

For cookie mode, the package checks the request header named by `AUTH_TRANSPORT_HEADER` and expects the value to be `cookie`.

Example:

```http
X-Auth-Transport: cookie
```

If the transport is `header`, the response is returned in JSON with `access_token` and `refresh_token`.

### 4. MFA verification

If `MFA_ENABLED` is enabled, login does not immediately return tokens. Instead, the package creates an MFA session and sends an OTP code to the user's email.

The response looks like:

```json
{
  "message": "Verification code sent.",
  "mfa_required": true,
  "mfa_token": "<uuid>"
}
```

Then the user calls:

```http
POST /verify/mfa/
```

Payload:

```json
{
  "mfa_token": "<uuid>",
  "otp": "123456"
}
```

If the OTP is correct, the user gets a normal login response with access/refresh tokens.

### 5. Refresh tokens

Send a refresh request to:

```http
POST /refresh/
```

For header transport, send:

```json
{
  "refresh_token": "<refresh token>"
}
```

For cookie transport, the refresh token is read from the refresh cookie automatically.

### 6. Logout

Logout is available at:

```http
POST /logout/
```

For header transport, send the refresh token in the request body. For cookie transport, the refresh cookie is used automatically.

### 7. Logout from all devices

This endpoint invalidates the current session version across all devices:

```http
POST /logout-all/
```

The package increments `token_version` and therefore invalidates all previously issued refresh tokens that belonged to the old version.

### 8. Password reset

The package exposes password reset endpoints:

```http
POST /forgot-password/
GET /verify/password-reset/<uuid:token>/
POST /reset-password-confirm/
```

Flow:

1. User submits their email or username to `/forgot-password/`.
2. A password reset email is sent if the account exists.
3. The user clicks the reset link.
4. The frontend is redirected to `CLIENT_URL/reset-password` with the token in the URL query string.
5. The frontend sends the new password to `/reset-password-confirm/`.

### 9. OAuth login

Enable OAuth with the `OAUTH_ENABLED` and `OAUTH_PROVIDERS` settings.

Each provider has its own URL:

```http
GET /oauth/google/
GET /oauth/github/
GET /oauth/facebook/
```

The provider redirects the user back to the callback endpoint:

```http
GET /oauth/<provider>/callback/
```

On success the package logs the user in and returns the same token response style as normal login.

## Endpoints overview

This package provides the following API endpoints:

- `POST /register/`
- `GET /verify/email/<uuid:token>/`
- `GET /user/`
- `POST /login/`
- `POST /verify/mfa/`
- `POST /refresh/`
- `POST /logout/`
- `POST /forgot-password/`
- `GET /verify/password-reset/<uuid:token>/`
- `POST /reset-password-confirm/`
- `POST /logout-all/`
- `GET /oauth/<provider>/`
- `GET /oauth/<provider>/callback/`

## Authentication transport

The package supports two transport styles:

### Header transport

This is the default style. The package returns tokens in the response body.

Use:

```http
X-Auth-Transport: header
```

### Cookie transport

The package writes token cookies and reads them from the browser automatically.

Use:

```http
X-Auth-Transport: cookie
```

The actual cookie names and properties come from the settings below.

## Full `AUTH_SETTINGS` reference

Every key below is read from `AUTH_SETTINGS`. If a key is missing, the package uses the default value shown in the right-hand column.

### Core email and account behavior

- `EMAIL_VERIFICATION` — When `True`, new users must verify their email before login. Default: `False`.
- `PASSWORD_RESET` — Intended to enable or expose password reset behavior. Default: `False`.
- `RESTRICT_MULTIPLE_LOGINS` — When `True`, every successful login increments `token_version`, so previously issued refresh tokens become invalid. Default: `False`.

### Cookie configuration

- `ACCESS_COOKIE_NAME` — Name of the access token cookie. Default: `"access_token"`.
- `REFRESH_COOKIE_NAME` — Name of the refresh token cookie. Default: `"refresh_token"`.
- `COOKIE_SECURE` — Whether cookies are marked secure. Default: `True`.
- `COOKIE_HTTP_ONLY` — Whether cookies are inaccessible to JavaScript. Default: `True`.
- `COOKIE_SAMESITE` — SameSite policy for cookies. Default: `"Lax"`.
- `ACCESS_COOKIE_PATH` — Cookie path for the access token. Default: `"/"`.
- `REFRESH_COOKIE_PATH` — Cookie path for the refresh token. Default: `"/"`.
- `COOKIE_DOMAIN` — Cookie domain. Default: `None`.
- `AUTH_TRANSPORT_HEADER` — Request header that tells the package whether to use header or cookie transport. Default: `"X-Auth-Transport"`.
- `ACCESS_COOKIE_MAX_AGE` — Access cookie lifetime in seconds. Default: `60 * 15` (15 minutes).
- `REFRESH_COOKIE_MAX_AGE` — Refresh cookie lifetime in seconds. Default: `60 * 60 * 24 * 7` (7 days).

### MFA settings

- `MFA_ENABLED` — Enables multi-factor authentication before token issuance. Default: `False`.
- `MFA_METHOD` — Current method selector for MFA. The built-in flow sends the code by email. Default: `"email"`.
- `MFA_CODE_LENGTH` — Length of the one-time password. Default: `6`.
- `MFA_EXPIRY` — Time in seconds before the MFA session expires. Default: `300`.
- `MFA_MAX_ATTEMPTS` — Maximum number of wrong OTP attempts allowed before the session is destroyed. Default: `5`.

### Password reset settings

- `PASSWORD_RESET_EXPIRY` — Number of seconds a password reset link/session stays valid. Default: `60 * 30`.
- `PASSWORD_RESET_URL` — Frontend reset URL used as a reference in the reset flow. Default: `"http://localhost:3000/reset-password"`.

### OAuth settings

- `OAUTH_ENABLED` — Enables OAuth endpoints and provider processing. Default: `False`.
- `OAUTH_PROVIDERS` — Provider configuration dictionary. Built-in providers are: `google`, `github`, and `facebook`.
- `STORE_PROVIDER_TOKENS` — When `True`, the package stores provider access tokens and related OAuth metadata on the local `OAuthAccount` model. Default: `False`.
- `SYNC_OAUTH_AVATAR` — When `True`, the package syncs the user's avatar from the OAuth provider when it is available and the user does not already have one. Default: `True`.

## OAuth provider configuration example

You can configure providers in `AUTH_SETTINGS` like this:

```python
AUTH_SETTINGS = {
    "OAUTH_ENABLED": True,
    "OAUTH_PROVIDERS": {
        "google": {
            "ENABLED": True,
            "CLIENT_ID": "your-google-client-id",
            "CLIENT_SECRET": "your-google-client-secret",
            "REDIRECT_URI": "http://localhost:8000/oauth/google/callback/",
            "SCOPES": ["openid", "email", "profile"],
        },
        "github": {
            "ENABLED": True,
            "CLIENT_ID": "your-github-client-id",
            "CLIENT_SECRET": "your-github-client-secret",
            "REDIRECT_URI": "http://localhost:8000/oauth/github/callback/",
            "SCOPES": ["read:user", "user:email"],
        },
        "facebook": {
            "ENABLED": True,
            "CLIENT_ID": "your-facebook-client-id",
            "CLIENT_SECRET": "your-facebook-client-secret",
            "REDIRECT_URI": "http://localhost:8000/oauth/facebook/callback/",
        },
    },
    "STORE_PROVIDER_TOKENS": True,
    "SYNC_OAUTH_AVATAR": True,
}
```

## Recommended beginner setup

If you are new to the package, the easiest starter configuration is:

```python
AUTH_SETTINGS = {
    "EMAIL_VERIFICATION": True,
    "PASSWORD_RESET": True,
    "MFA_ENABLED": False,
    "COOKIE_SECURE": False,
    "COOKIE_HTTP_ONLY": True,
    "COOKIE_SAMESITE": "Lax",
    "AUTH_TRANSPORT_HEADER": "X-Auth-Transport",
    "OAUTH_ENABLED": False,
}
```

Start with header transport first, because it is the simplest to inspect in JSON responses. Once your frontend is stable, switch to cookie transport.

## Notes for production

For production deployment:

- use `COOKIE_SECURE = True`
- set your real `CLIENT_URL` and `BACKEND_URL`
- provide valid OAuth credentials for each provider
- use secure environment variables instead of hard-coded secrets
- keep `MFA_ENABLED` on for stronger protection when handling sensitive user accounts

