Security

JsWeb provides helpers for common security tasks, primarily password hashing. For this, it uses the robust and well-tested Werkzeug security module and simply re-exports its hashing functions for convenience.

You should never store plain-text passwords in your database. Always store the hashed version.

generate_password_hash(password)

Takes a plain-text password as a string and returns a salted and hashed version of it, suitable for storing in your database. The hashing method (e.g., pbkdf2:sha256) and salt are included in the output string itself.

Example: Hashing a password during registration

from jsweb.security import generate_password_hash
from .models import User

# ... inside a registration view ...
form = RegistrationForm(req.form)
if req.method == 'POST' and form.validate():
    # Hash the password before storing it
    hashed_password = generate_password_hash(form.password.data)
    new_user = User.create(
        username=form.username.data,
        email=form.email.data,
        password_hash=hashed_password  # Store the hash, not the plain password
    )
    # ... log the user in and redirect ...

check_password_hash(pwhash, password)

Compares a previously generated password hash (retrieved from your database) with a plain-text password that a user is attempting to log in with. It returns True if the password is correct and False otherwise.

Example: Checking a password during login

from jsweb.security import check_password_hash
from .models import User

# ... inside a login view ...
form = LoginForm(req.form)
if req.method == 'POST' and form.validate():
    user = User.query.filter_by(username=form.username.data).first()
    
    # Check if the user exists and the password is correct
    if user and check_password_hash(user.password_hash, form.password.data):
        # Password is correct, log the user in
        response = redirect('/dashboard')
        login_user(response, user)
        return response
    
    # If user not found or password incorrect, show an error
    # ...