A wristband at a festival
At a festival, you show your ticket once at the gate. You get a wristband. After that, every stage just checks the wristband.
Some areas need a special band, such as backstage.
A web app works the same way. You sign in once. Each page then checks who you are and what you may see.
Key words
| Word | What it means | Example |
|---|---|---|
| Authentication | Checking who somebody is. | email and password |
| Authorisation | Checking what somebody is allowed to do. | |
| Session | What the app remembers about you between pages. | |
| Cookie | A small piece of data the browser sends back with every request. | |
| Decorator | A line starting with @ that wraps extra checks around a function (a named block of code). | |
| Role | The kind of user, which decides what they may do. | tier1 |
The cells students fill in are left blank in this preview.
By the end of this lesson
Note
I can protect pages so that only signed-in users with the right role can open them.
Starter: what you already know
Have a go
Starter: what you already know
3 questionsSprint 1, step 4: the goal and stories
| Part | For this step |
|---|---|
| Sprint (a short block of work) | Sprint 1: people sign in and handle support requests. |
| E1.1 | As any user, I want to sign in with my email and password, so that I see my own work. |
| E1.2 | As a manager, I want each role to see only its own pages, so that data stays safe. |
| E1.3 | As any user, I want to sign out, so that nobody else uses my account. |
The cells students fill in are left blank in this preview.
The session remembers who you are
After a good sign in, the app saves your user id in the session. Flask keeps the session in a cookie, signed with a secret key. Nobody can change the cookie without the key.
Before every request, load_signed_in_user() reads the id and loads the user into g.user. Every page and template can use it.
The secret key comes from the computer's settings, never from the code in Git.
Step 4: who is signed in?
# helpdesk/auth.py (part)
@bp.before_app_request
def load_signed_in_user():
"""Runs before every request, so every page can use g.user."""
user_id = session.get("user_id")
g.user = db.session.get(User, user_id) if user_id else None
def login_required(view):
"""Put @login_required above a page that needs a signed-in user."""
@wraps(view)
def wrapped(*args, **kwargs):
if g.user is None:
flash("Please sign in to see that page.")
return redirect(url_for("auth.signin"))
return view(*args, **kwargs)
return wrapped
Make a free account to save your work and track your progress.
Check: sessions
Have a go
Check: sessions
3 questionsA decorator guards a page
Writing "is anyone signed in?" at the top of every page would mean copying the same lines many times.
Instead, login_required is a decorator. You put @login_required above a page. It runs its check first. If nobody is signed in, it sends them to the sign in page with a message. If they are, the page runs as normal.
This step writes it by hand, so you can see exactly how it works.
Try it: a decorator in plain Python
from functools import wraps
signed_in_user = None # nobody is signed in yet
def login_required(view):
@wraps(view)
def wrapped():
if signed_in_user is None:
return "Please sign in to see that page."
return view()
return wrapped
@login_required
def dashboard():
return "Hello, " + signed_in_user + ". Here is your dashboard."
print(dashboard())
# Change None to "Maya Patel", then press Run again.
Make a free account to save your work and track your progress.
Signing in gives one careful message
The sign in page looks up the email, then checks the password against the hash.
If either is wrong, it says the same thing: the email address or password is not right. A different message for each would tell a stranger which emails have accounts.
It also turns the email into small letters, so Maya@... and maya@... are the same person.
Step 4: the sign in route
# helpdesk/auth.py (part)
@bp.route("/signin", methods=["GET", "POST"])
def signin():
error = None
email = ""
if request.method == "POST":
email = request.form.get("email", "").strip().lower()
given_password = request.form.get("password", "")
user = db.session.scalar(db.select(User).where(User.email == email))
# The same message whether the email or the password is wrong, so the
# page does not tell a stranger which emails have accounts.
if user is None or not user.check_password(given_password):
error = "The email address or password is not right."
else:
# Start a fresh session, so nothing from before signing in is kept.
session.clear()
session["user_id"] = user.id
flash(f"Signed in as {user.name}.")
return redirect(url_for("main.dashboard"))
return render_template("signin.html", error=error, email=email)
Make a free account to save your work and track your progress.
Check: signing in
Have a go
Check: signing in
3 questionsRoles decide what each user may do
Signing in is authentication. Deciding what you may do is authorisation.
role_required("manager") checks the user's role. A signed-in user with the wrong role gets error 403, which means forbidden.
Signing out is a button in a small form, not a link. That way another website cannot sign you out by showing a link to the address.
Step 4: role_required
# helpdesk/auth.py (part)
def role_required(*roles):
"""Put @role_required("manager") above a page for some roles only."""
def decorator(view):
@wraps(view)
def wrapped(*args, **kwargs):
if g.user is None:
flash("Please sign in to see that page.")
return redirect(url_for("auth.signin"))
if g.user.role not in roles:
abort(403) # 403 means "Forbidden": signed in, but not allowed
return view(*args, **kwargs)
return wrapped
return decorator
Make a free account to save your work and track your progress.
A common mistake
Warning
Many students think hiding a menu link protects a page. It does not. Anyone can type the address. Every protected page needs a check on the server, such as @role_required. Hiding the link only makes the menu tidier.
Match each idea to its meaning
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Build it yourself: step 4
Build step 4. 1. Set a secret key from the environment in create_app, with a random one as a fallback on your own computer. 2. Write auth.py with load_signed_in_user, login_required, role_required, a sign in route and a sign out route that only accepts POST. 3. Make signin.html with labelled fields and an error box, and a dashboard that greets the user by role. 4. Show flash messages in base.html. 5. Test by hand: a right and a wrong password, a page opened while signed out, and a page opened with the wrong role. Write what happened each time. 6. Commit and write the change log row.
A teacher marks this in a college. Nothing you write here is kept: it goes when you leave the page.
Make a free account to save your work, or press Start lab to work through the whole lesson.
Compare with the step 4 code
Tip
Compare yours with the step 4 code on GitHub. Sign in as each demo role and check what the dashboard says.
Change log entry for step 4
| Date | Version and files | What changed | Why |
|---|---|---|---|
| 5 March | step-04: auth.py, main.py, __init__.py, signin.html, dashboard.html, base.html | Sign in and out, the session, login_required and role_required by hand, a secret key, a dashboard | Almost every later page depends on who is signed in and their role |
The cells students fill in are left blank in this preview.
Next: raise a support request
Now the app knows who you are. In step 5 a customer raises a support request. The server checks every field and explains any problem in plain words.
Exit quiz
Have a go