Authentication
JsWeb provides a simple and secure session-based authentication system. It uses a timed serializer to create secure session cookies.
Initialization
The authentication system is initialized automatically by the JsWebApp
instance if a SECRET_KEY
is present in the configuration. It calls init_auth
internally.
User Loader
The authentication system needs a way to load a user from the database given a user ID. You must provide a "user loader" function. By default, JsWeb looks for a User
model in a models.py
file and tries to call User.query.get(user_id)
. You can override this behavior by setting the _user_loader_callback
on your app instance.
# In app.py, after creating the app instance
from models import User
def my_user_loader(user_id):
return User.get_by_id(user_id) # Assuming you have a custom method
app._user_loader_callback = my_user_loader
Functions
login_user(response, user)
Logs a user in by creating a secure, HTTP-only session cookie. You must pass the response
object to this function so the cookie can be set.
from jsweb.auth import login_user
from jsweb.response import redirect
@app.route('/login', methods=['POST'])
def login(req, res):
# ... validate user credentials ...
user = get_user_from_db(req.form['username'])
if user and user.check_password(req.form['password']):
response = redirect('/profile')
login_user(response, user)
return response
# ... handle failed login ...
logout_user(response)
Logs a user out by deleting the session cookie. Like login_user
, this requires the response
object.
from jsweb.auth import logout_user
from jsweb.response import redirect
@app.route('/logout')
def logout(req, res):
response = redirect('/login')
logout_user(response)
return response
get_current_user(request)
Retrieves the currently logged-in user from the session cookie in the request. This is done automatically by the framework, and the user object is attached to the request
object as request.user
.
@app.route('/profile')
def profile(req, res):
if req.user:
return f"Hello, {req.user.username}!"
return "You are not logged in."
Decorator
@login_required
A decorator to protect routes from unauthenticated access. If a user is not logged in, they will be redirected to the login page (as defined by the URL for the endpoint 'auth.login').
from jsweb.auth import login_required
@app.route('/dashboard')
@login_required
def dashboard(req, res):
# This view can only be accessed by logged-in users.
# The user object is guaranteed to be available on req.user.
return f"Welcome to your dashboard, {req.user.username}!"