Refactoring
NotesAs previously demonstrated, there are now a number of tweaks that can be made to views and templates, to control what is accessible and what gets rendered depending on whether a user is logged in or not.
Every page knows the user#
The navigation should show different links to visitors, logged-in users and authors. The navigation lives in _base.html, which every page uses, so every view needs to include the current user in its context. Let’s start with the home page:
from fastapi import APIRouter, status, Request, Depends
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from sqlmodel import Session
from api.auth_apis import is_user
from api.blog_apis import get_blogposts_api
from db.db import get_session_db
router = APIRouter()
templates = Jinja2Templates('web/templates')
@router.get('/', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def home_view(*, request: Request, session: Session = Depends(get_session_db)):
blogposts = get_blogposts_api(limit=3, session=session)
current_user = is_user(request, session)
context = {
"page": "home",
"blogposts": blogposts,
"user": current_user
}
return templates.TemplateResponse(request, 'home.html', {'context': context})is_user returns None for visitors who aren’t logged in, so public pages like this one carry on working for everyone. Only pages that need a login redirect to the login page.
By including the user in the context, the navigation in _base.html can now be rendered one way or another:
<ul class="nav navbar-nav navbar-right">
<li{% if context.page == 'home' %} class="active"{% endif %}>
<a href="/">Home</a>
</li>
<li{% if context.page == 'contact' %} class="active"{% endif %}>
<a href="/contact">Contact</a>
</li>
{% if context.user %}
{% if context.user.is_author %}
<li{% if context.page == 'create' %} class="active"{% endif %}>
<a href="/blog/create">Create</a>
</li>
{% endif %}
<li>
<a href="/auth/logout">Logout</a>
</li>
{% else %}
<li{% if context.page == 'login' %} class="active"{% endif %}>
<a href="/auth/login">Login</a>
</li>
{% endif %}
</ul>In each view’s context, I’ve been including a page name. The navigation exploits that to mark the page a user is currently viewing as active, which the Bootstrap theme highlights. Only authors see the Create link.
So, now if a user is logged in:
And if a user is not logged in:
Remember to include the user in every view’s context, for example in contact_view.py:
context = {
"page": "contact",
"captcha_id": create_captcha(session).id,
"user": is_user(request, session), # NEW
}Authors only#
Next, update the functions blogpost_create_get_view, blogpost_create_post_view, blogpost_update_get_view, blogpost_update_post_view, and blogpost_delete_post_view to check the user is logged in and an author:
current_user = is_user(request, session)
if current_user is None:
return RedirectResponse(url='/auth/login', status_code=status.HTTP_303_SEE_OTHER)
if not current_user.is_author:
return RedirectResponse(url='/', status_code=status.HTTP_303_SEE_OTHER)It’s important to check in the POST functions too, not just in the GET functions that show the forms. Hiding a form or a link doesn’t stop anyone sending the request directly, for example with curl. The POST functions need a request: Request parameter for this.
Sure, there are a number of clever things that could be done here, such as using FastAPI dependencies or decorators, but in the name of keeping things clear we’ll stick to this approach. In the next section a further check will be added to make sure users can’t update or delete other users’ content.
The blog post page only shows the Edit and Delete buttons to authors:
{% if context.user and context.user.is_author %}
<br>
<a href="/blog/update/{{ context.post.id }}" class="btn btn-default">Edit</a>
<form action="/blog/delete/{{ context.post.id }}" method="post" style="display: inline"
onsubmit="return confirm('Are you sure?')">
<button type="submit" class="btn btn-default">Delete</button>
</form>
{% endif %}Here is the complete web/views/blog_views.py at this point:
import uuid
import markdown
import nh3
from fastapi import APIRouter, status, Request, Depends, Form, UploadFile, File
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlmodel import Session
from api.auth_apis import is_user
from api.blog_apis import get_blogpost_by_id_api, create_blogpost_api, update_blogpost_api, delete_blogpost_by_id_api
from db.db import get_session_db
from db.schemas.blog_schemas import BlogPostIn
from web.images import save_cover_image
router = APIRouter()
templates = Jinja2Templates('web/templates')
WORDS_PER_MINUTE = 265
def read_time_minutes(text: str) -> int:
return max(1, round(len(text.split()) / WORDS_PER_MINUTE))
@router.get('/blog/create', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def blogpost_create_get_view(*, request: Request, session: Session = Depends(get_session_db)):
current_user = is_user(request, session)
if current_user is None:
return RedirectResponse(url='/auth/login', status_code=status.HTTP_303_SEE_OTHER)
if not current_user.is_author:
return RedirectResponse(url='/', status_code=status.HTTP_303_SEE_OTHER)
context = {
"page": "create",
"user": current_user
}
return templates.TemplateResponse(request, 'blog_create.html', {'context': context})
@router.post('/blog/create', response_class=HTMLResponse)
def blogpost_create_post_view(*,
request: Request,
title: str = Form(...),
teaser: str = Form(...),
content: str = Form(...),
cover_image: UploadFile = File(...),
published: bool = Form(False),
session: Session = Depends(get_session_db)):
current_user = is_user(request, session)
if current_user is None:
return RedirectResponse(url='/auth/login', status_code=status.HTTP_303_SEE_OTHER)
if not current_user.is_author:
return RedirectResponse(url='/', status_code=status.HTTP_303_SEE_OTHER)
cover_image_path = save_cover_image(cover_image)
new_blogpost = BlogPostIn(title=title, teaser=teaser, content=content,
cover_image=cover_image_path, published=published)
post = create_blogpost_api(blogpost_in=new_blogpost, session=session)
return RedirectResponse(f'/blog/{post.id}', status_code=status.HTTP_303_SEE_OTHER)
@router.get('/blog/update/{id}', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def blogpost_update_get_view(*, id: uuid.UUID, request: Request, session: Session = Depends(get_session_db)):
current_user = is_user(request, session)
if current_user is None:
return RedirectResponse(url='/auth/login', status_code=status.HTTP_303_SEE_OTHER)
if not current_user.is_author:
return RedirectResponse(url='/', status_code=status.HTTP_303_SEE_OTHER)
post = get_blogpost_by_id_api(id=id, session=session)
context = {
"page": "blog_update",
"post": post,
"user": current_user
}
return templates.TemplateResponse(request, 'blog_update.html', {'context': context})
@router.post('/blog/update/{id}', response_class=HTMLResponse)
def blogpost_update_post_view(*,
id: uuid.UUID,
request: Request,
title: str = Form(...),
teaser: str = Form(...),
content: str = Form(...),
cover_image: UploadFile | None = File(None),
published: bool = Form(False),
session: Session = Depends(get_session_db)):
current_user = is_user(request, session)
if current_user is None:
return RedirectResponse(url='/auth/login', status_code=status.HTTP_303_SEE_OTHER)
if not current_user.is_author:
return RedirectResponse(url='/', status_code=status.HTTP_303_SEE_OTHER)
post = get_blogpost_by_id_api(id=id, session=session)
cover_image_path = post.cover_image
if cover_image and cover_image.filename:
cover_image_path = save_cover_image(cover_image)
blogpost_updates = BlogPostIn(title=title, teaser=teaser, content=content,
cover_image=cover_image_path, published=published)
update_blogpost_api(id=id, data=blogpost_updates, session=session)
return RedirectResponse(f'/blog/{id}', status_code=status.HTTP_303_SEE_OTHER)
@router.post('/blog/delete/{id}', response_class=HTMLResponse)
def blogpost_delete_post_view(*, id: uuid.UUID, request: Request, session: Session = Depends(get_session_db)):
current_user = is_user(request, session)
if current_user is None:
return RedirectResponse(url='/auth/login', status_code=status.HTTP_303_SEE_OTHER)
if not current_user.is_author:
return RedirectResponse(url='/', status_code=status.HTTP_303_SEE_OTHER)
delete_blogpost_by_id_api(id=id, session=session)
return RedirectResponse('/', status_code=status.HTTP_303_SEE_OTHER)
@router.get('/blog/{id}', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def blogpost_get_view(*, id: uuid.UUID, request: Request, session: Session = Depends(get_session_db)):
post = get_blogpost_by_id_api(id=id, session=session)
markdown_content = nh3.clean(markdown.markdown(post.content))
context = {
"page": "blog",
"post": post,
"markdown": markdown_content,
"blogpost_readtime": read_time_minutes(post.content),
"user": is_user(request, session),
}
return templates.TemplateResponse(request, 'blogpost.html', {'context': context})Testing#
The example code includes test_auth.py, which tests creating users (and that the password is hashed and never returned), the token API, the login form and its cookie settings, that only authors can create posts, that an expired or tampered-with token simply means “logged out”, deactivated users and logging out. conftest.py gained helpers to create users and an author_client fixture: a test client that’s already logged in as an author, which the blog tests now use.
Two settings are changed for the tests, before the application is imported: CONF_ENABLE_APIS=true, because the API tests need the API routes, and CONF_AUTH_COOKIE_SECURE=false, because the test client uses plain http://, so it wouldn’t send a secure cookie back.
The example code at this point is tagged ch06-authentication in the example repository. To get it:
git clone https://github.com/codewalkr/fastapi-example-for-you.git
cd fastapi-example-for-you
git checkout ch06-authentication