plain.auth
Add users to your app and decide what they can access.
- Overview
- Authentication setup
- Checking if a user is logged in
- Restricting views
- Testing with authenticated users
- Settings
- FAQs
- Installation
Overview
The plain.auth package handles user authentication and authorization for Plain applications. You can check if a user is logged in like this:
from plain.auth import get_request_user
user = get_request_user(request)
if user:
print(f"Hello, {user.email}!")
else:
print("You are not logged in.")
You can restrict a view to logged-in users using AuthViewMixin:
from plain.auth.views import AuthViewMixin
from plain.views import View
class ProfileView(AuthViewMixin, View):
login_required = True
def get(self):
return f"Welcome, {self.user.email}!"
Authentication setup
Settings configuration
Configure your authentication settings in app/settings.py:
INSTALLED_PACKAGES = [
# ...
"plain.auth",
"plain.sessions",
"plain.passwords", # Or another auth method
"app.users",
]
MIDDLEWARE = [
"plain.sessions.middleware.SessionMiddleware",
"plain.auth.middleware.AuthMiddleware",
]
AUTH_LOGIN_URL = "login"
Creating a user model
plain.auth expects your project's User class at app.users.models.User — a fixed convention, not a configurable setting. The package label (users), module (models.py), and class name (User) are all required.
You can create one with plain create users or manually:
# app/users/models.py
from datetime import datetime
from plain import postgres
from plain.postgres import Field, types
from plain.passwords.models import PasswordField
@postgres.register_model
class User(postgres.Model):
email: Field[str] = types.EmailField()
password: Field[str] = PasswordField()
is_admin: Field[bool] = types.BooleanField(default=False)
created_at: Field[datetime] = types.DateTimeField(create_now=True)
def __str__(self):
return self.email
Login views
To log users in, you need to pair this package with an authentication method:
- plain.passwords - Username/password authentication
- plain.oauth - OAuth provider authentication
- plain.loginlink - Magic link authentication
Here's an example with password authentication:
# app/urls.py
from plain.auth.views import LogoutView
from plain.urls import path
from plain.passwords.views import PasswordLoginView
class LoginView(PasswordLoginView):
template_name = "login.html"
urlpatterns = [
path("logout/", LogoutView, name="logout"),
path("login/", LoginView, name="login"),
]
Checking if a user is logged in
In templates, you can use the get_current_user() function:
{% if get_current_user() %}
<p>Hello, {{ get_current_user().email }}!</p>
{% else %}
<p>You are not logged in.</p>
{% endif %}
In Python code, use get_request_user():
from plain.auth import get_request_user
user = get_request_user(request)
if user:
print(f"Hello, {user.email}!")
else:
print("You are not logged in.")
Restricting views
You can use AuthViewMixin to restrict views to logged-in users, admin users, or custom logic:
from plain.auth.views import AuthViewMixin
from plain.http import ForbiddenError403
from plain.views import View
class LoggedInView(AuthViewMixin, View):
login_required = True
class AdminOnlyView(AuthViewMixin, View):
login_required = True
admin_required = True
class CustomPermissionView(AuthViewMixin, View):
def check_auth(self):
super().check_auth()
if not self.user.is_special:
raise ForbiddenError403("You're not special!")
The AuthViewMixin provides:
login_required- Requires a logged-in useradmin_required- Requiresuser.is_adminto be Truecheck_auth()- Override for custom authorization logic
Testing with authenticated users
When writing tests, you can use login_client() to simulate an authenticated user:
from plain.auth.testing import login_client
from plain.testing import Client
from app.users.models import User
def test_profile_view():
user = User.query.create(email="test@example.com")
client = Client()
login_client(client, user)
response = client.get("/profile/")
assert response.status_code == 200
It writes the session cookie to the client, so every request the client makes afterwards is that user's. Nothing goes through your login view.
logout_client() ends the session and drops the client's cookies:
from plain.auth.testing import login_client, logout_client
# ... after logging in
logout_client(client)
assert client.get("/profile/").status_code == 302
To check who a request was authenticated as, read the user from the request the response came from:
from plain.auth.requests import get_request_user
response = client.get("/profile/")
assert get_request_user(response.request) == user
Settings
| Setting | Default | Env var |
|---|---|---|
AUTH_LOGIN_URL |
Required | PLAIN_AUTH_LOGIN_URL |
AUTH_USER_SESSION_HASH_FIELD |
"password" or "" |
PLAIN_AUTH_USER_SESSION_HASH_FIELD |
See default_settings.py for more details.
FAQs
How do I log in a user programmatically?
You can use the login() function to log in a user:
from plain.auth.sessions import login
login(request, user)
How do I log out a user programmatically?
You can use the logout() function:
from plain.auth.sessions import logout
logout(request)
How do I invalidate sessions when a user changes their password?
By default, if you have plain.passwords installed, sessions are automatically invalidated when the password field changes. This is controlled by the AUTH_USER_SESSION_HASH_FIELD setting. You can change this to a different field name, or set it to an empty string to disable this feature.
How do I reference the User class?
Import it directly from app.users.models — the location is fixed:
from app.users.models import User
Installation
Install the plain.auth package from PyPI:
uv add plain.auth
Metadata
Release files for plain.auth 0.31.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| plain_auth-0.31.0.tar.gz | 20.2 kB | Without provenance | Details for plain_auth-0.31.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| plain_auth-0.31.0-py3-none-any.whl | Python 3 | none | any | Details for plain_auth-0.31.0-py3-none-any.whl |
Total release size: 41.7 kB
Release files / plain_auth-0.31.0.tar.gz
| Download URL | plain_auth-0.31.0.tar.gz |
|---|---|
| Size | 20.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ae7a2f72e6f092b42425a8d8d9d10eca975c9da56b904d3bdde751f4ae260cbf
|
|
BLAKE2b-256 checksum How to use checksums |
31146200cd21596e9c773918ecd78d8632229e98c77068dd6f98c62c2ef6e105
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.12.23 {"installer":{"name":"uv","version":"0.12.23","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / plain_auth-0.31.0-py3-none-any.whl
| Download URL | plain_auth-0.31.0-py3-none-any.whl |
|---|---|
| Size | 21.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2fcaa1acca3cbd8d750ec3a46ba9015e5c91b3073b8073273733ff71d2e6d176
|
|
BLAKE2b-256 checksum How to use checksums |
4f1d203c9c9c4068dab969031565c0222db43339875235c4530d915423d65e24
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.12.23 {"installer":{"name":"uv","version":"0.12.23","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for plain.auth 0.31.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.