# authentication

[!badge New in 2.8.0!]

Spiderweb ships with a small built-in authentication system: a `User` model, a `Permission` model, and three helper functions -- `authenticate()`, `login()`, and `logout()`. It's deliberately minimal, but it covers the common case of "let visitors log in and stay logged in."

Authentication relies on sessions, so make sure the sessions middleware is enabled:

```python
from spiderweb import SpiderwebRouter

app = SpiderwebRouter(
    middleware=["spiderweb.middleware.sessions.SessionMiddleware"],
)
```

> Read more [about the sessions middleware here](middleware/sessions.md).

## The User model

The `User` model lives in `spiderweb.models` and is stored in your app's database (the same one configured via the `db` argument):

```python
from spiderweb.models import User
```

It has the fields you'd expect: `username` (unique), `email`, `first_name`, `last_name`, `password`, `is_active`, `is_staff`, `is_superuser`, `last_login`, and `date_joined`. Passwords are never stored in plain text -- `set_password()` hashes them with PBKDF2-SHA256, and `check_password()` verifies them:

```python
db = app.get_db_session()
user = User(username="testuser", email="test@example.com")
user.set_password("password")
db.add(user)
db.commit()
db.close()
```

A few useful helpers on the model:

- `user.check_password("password")` -- returns `True`/`False`
- `user.has_usable_password()` -- `False` if the password was set to unusable
- `user.is_authenticated` / `user.is_anonymous` -- always `True`/`False` for a real user
- `user.get_full_name()` / `user.get_short_name()` / `user.get_username()`

## Logging users in and out

The `spiderweb.authentication` module gives you three functions:

```python
from spiderweb.authentication import authenticate, login, logout
```

- `authenticate(request, username=..., password=...)` -- looks up the user and checks the password. Returns the `User` on success, `None` on failure.
- `login(request, user)` -- stores the user's id in the session, so they stay logged in on subsequent requests.
- `logout(request)` -- clears the session and resets `request.user` to an anonymous user.

Here's a typical login/logout pair of views:

```python
from spiderweb.authentication import authenticate, login, logout
from spiderweb.response import RedirectResponse

@app.route("/login", allowed_methods=["POST"])
def do_login(request):
    user = authenticate(
        request,
        username=request.POST.get("username"),
        password=request.POST.get("password"),
    )
    if user:
        login(request, user)
    return RedirectResponse("/")

@app.route("/logout", allowed_methods=["POST"])
def do_logout(request):
    logout(request)
    return RedirectResponse("/")
```

> If your login form posts with CSRF protection enabled, either include the CSRF token in the form or mark the view `csrf_exempt`. See [the CSRF middleware](middleware/csrf.md).

## request.user

Once the sessions middleware is active, every request gets a `user` attribute. If the visitor is logged in, it's their `User` object; otherwise it's an `AnonymousUser` with `is_authenticated == False`. Checking whether someone is logged in is therefore just:

```python
@app.route("/")
def index(request):
    if request.user.is_authenticated:
        return HttpResponse(f"Hello, {request.user.username}!")
    return HttpResponse("Hello, stranger!")
```

`AnonymousUser` mirrors the same interface (`username`, `is_staff`, `is_superuser`, etc.), so you usually don't need to branch on the type -- just check `is_authenticated`.

## Permissions

[!badge New in 2.6.0!]

Users have a many-to-many relationship with the `Permission` model, available as `user.permissions`:

```python
from spiderweb.models import Permission

db = app.get_db_session()
perm = Permission(name="Can publish posts", codename="publish_post")
db.add(perm)
db.commit()

user.permissions.append(perm)
db.commit()
db.close()
```

Each `Permission` has a human-readable `name` and a unique `codename` you can check against in your views:

```python
@app.route("/publish", allowed_methods=["POST"])
def publish(request):
    if not request.user.is_authenticated:
        return RedirectResponse("/login")
    if not any(p.codename == "publish_post" for p in request.user.permissions):
        return HttpResponse("Forbidden", status_code=403)
    ...
```

## Full example

There's a complete, runnable version of all of this in the repo at `example_auth.py` -- spin it up with `python example_auth.py` and log in with `testuser` / `password`.
