Manage Users

The users page lists every user, with checkboxes for what they’re allowed to do, and buttons to update or delete them.

Schema#

Updating a user from the admin pages only changes their flags, so add a schema with just those fields:

db/schemas/user_schemas.pypython
# For site administrators changing what a user can do
class UserUpdate(SQLModel):
    is_superuser: bool
    is_active: bool
    is_author: bool
    is_member: bool

APIs#

Add the user functions to the admin APIs. You’ll need to import UserOut, UserUpdate, AuthToken, HTTPException, delete and uuid:

api/admin_apis.pypython
# Users
@router.get('/admin/users', status_code=status.HTTP_200_OK)
def get_all_users_api(session: Session = Depends(get_session_db)) -> list[UserOut]:
    return session.exec(select(User).order_by(User.created_date.desc())).all()

@router.put('/admin/users/{id}', status_code=status.HTTP_200_OK)
def update_user_api(id: uuid.UUID, data: UserUpdate, session: Session = Depends(get_session_db)) -> UserOut:
    user = session.get(User, id)
    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"No user found with id {id}.")
    user.sqlmodel_update(data.model_dump())
    session.add(user)
    session.commit()
    session.refresh(user)
    return user

@router.delete('/admin/users/{id}', status_code=status.HTTP_204_NO_CONTENT)
def delete_user_by_id_api(id: uuid.UUID, session: Session = Depends(get_session_db)) -> None:
    user = session.get(User, id)
    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"No user found with id {id}.")
    # Their posts and comments stay, without an author (SQLAlchemy sets the
    # foreign keys to NULL); their email and password reset links go
    session.exec(delete(AuthToken).where(AuthToken.user_id == id))
    session.delete(user)
    session.commit()
  • update_user_api copies the four flags onto the user with sqlmodel_update, the same as the blog post update.
  • delete_user_by_id_api deletes the user, but not what they wrote. When a user is deleted, SQLAlchemy sets blogpost_author_id and comment_author_id to NULL on their posts and comments, because the User relationships don’t ask for a cascade. (The blog post’s comments, on the other hand, are deleted with the post, because of cascade_delete=True.) Their email verification and password reset tokens are deleted explicitly.

Views#

web/views/admin_views.pypython
# Users
@router.get('/admin/users', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def admin_users_view(*, request: Request, session: Session = Depends(get_session_db)):
    current_user = get_superuser(request, session)
    if current_user is None:
        return not_allowed()

    context = {
        "page": "users",
        "user": current_user,
        "users": get_all_users_api(session=session),
    }

    return templates.TemplateResponse(request, 'admin/users.html', {'context': context})

@router.post('/admin/users/{id}/update', response_class=HTMLResponse)
def admin_user_update_view(*,
                           id: uuid.UUID,
                           request: Request,
                           is_superuser: bool = Form(False),
                           is_active: bool = Form(False),
                           is_author: bool = Form(False),
                           is_member: bool = Form(False),
                           session: Session = Depends(get_session_db)):
    current_user = get_superuser(request, session)
    if current_user is None:
        return not_allowed()
    # Stop administrators locking themselves out
    if id == current_user.id:
        is_superuser, is_active = True, True

    user_updates = UserUpdate(is_superuser=is_superuser, is_active=is_active,
                              is_author=is_author, is_member=is_member)
    update_user_api(id=id, data=user_updates, session=session)
    return RedirectResponse('/admin/users', status_code=status.HTTP_303_SEE_OTHER)

@router.post('/admin/users/{id}/delete', response_class=HTMLResponse)
def admin_user_delete_view(*, id: uuid.UUID, request: Request, session: Session = Depends(get_session_db)):
    current_user = get_superuser(request, session)
    if current_user is None:
        return not_allowed()
    if id != current_user.id:
        delete_user_by_id_api(id=id, session=session)
    return RedirectResponse('/admin/users', status_code=status.HTTP_303_SEE_OTHER)

Unticked checkboxes aren’t sent at all, so each flag defaults to False, and a ticked one arrives as on, which becomes True.

Two safety checks stop an administrator locking themselves out: they can’t remove their own superuser or active status, or delete themselves. Otherwise a slip of the mouse could leave the site with no administrators.

Template#

web/templates/admin/users.htmljinja
{% extends "admin/_base.html" %}

{% block content %}
<h2>Users</h2>
<hr>
<table class="table table-striped">
    <thead>
    <tr>
        <th>Name</th>
        <th>Email</th>
        <th>Joined</th>
        <th>Superuser</th>
        <th>Active</th>
        <th>Author</th>
        <th>Member</th>
        <th></th>
        <th></th>
    </tr>
    </thead>
    <tbody>
    {% for user in context.users %}
    <tr>
        <td>{{ user.first_name }} {{ user.last_name }}</td>
        <td>{{ user.email }}</td>
        <td>{{ user.created_date.strftime('%d %b %Y') }}</td>
        {% for flag in ['is_superuser', 'is_active', 'is_author', 'is_member'] %}
        <td><input type="checkbox" name="{{ flag }}" form="update-{{ user.id }}" {% if user[flag] %}checked{% endif %}
                   {% if user.id == context.user.id and flag in ['is_superuser', 'is_active'] %}disabled{% endif %}></td>
        {% endfor %}
        <td>
            <form action="/admin/users/{{ user.id }}/update" method="post" id="update-{{ user.id }}">
                <button type="submit" class="btn btn-sm btn-primary">Update</button>
            </form>
        </td>
        <td>
            {% if user.id != context.user.id %}
            <form action="/admin/users/{{ user.id }}/delete" method="post" onsubmit="return confirm('Delete {{ user.email }}?')">
                <button type="submit" class="btn btn-sm btn-danger">Delete</button>
            </form>
            {% endif %}
        </td>
    </tr>
    {% endfor %}
    </tbody>
</table>
<p><small>You can't remove your own superuser or active status, or delete yourself.</small></p>
{% endblock %}

Each row has its own update form, in the last-but-one cell. HTML doesn’t allow a form to wrap a table row, so the checkboxes in the other cells join the form with the form="update-..." attribute, which links an input to a form by its id.

user[flag] reads an attribute by name, so one loop draws all four checkboxes. The current administrator’s own superuser and active boxes are disabled.