Change Password

change_password

An endpoint where the authenticated user can change their password. If you send a GET request to this endpoint, a simple form is shown in which the user can change their password manually.

../_images/change_password.png

Hint

You can use a custom template, which matches the look and feel of your application. See the template_path parameter. Or specify custom CSS styles using the styles parameter.

Alternatively, you can change the password programatically by sending a POST request to this endpoint (passing in old_password, new_password and confirm_new_password parameters as JSON, or as form data).

When the password change is successful, we invalidate the session cookie, and redirect the user to the login endpoint.

Warning

Only authenticated users can change their passwords!

Example

In this example we show how the endpoint integrates with a Starlette app using session auth.

For the complete source code, see the demo project on GitHub.

from starlette.applications import Starlette
from starlette.endpoints import HTTPEndpoint
from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.requests import Request
from starlette.responses import HTMLResponse, RedirectResponse
from starlette.routing import Mount, Route

from piccolo_api.change_password.endpoints import change_password
from piccolo_api.csrf.middleware import CSRFMiddleware
from piccolo_api.register.endpoints import register
from piccolo_api.session_auth.endpoints import session_login
from piccolo_api.session_auth.middleware import SessionsAuthBackend


class HomeEndpoint(HTTPEndpoint):
    async def get(self, request):
        return HTMLResponse(
            content=(
                "<style>body{font-family: sans-serif;}</style>"
                "<h1>Change Password Demo</h1>"
                '<p>First <a href="/register/">register</a></p>'  # noqa: E501
                '<p>Then <a href="/login/">login</a></p>'  # noqa: E501
                '<p>Then try <a href="/private/change-password/">changing your password</a></p>'  # noqa: E501
            )
        )


def on_auth_error(request: Request, exc: Exception):
    return RedirectResponse("/login/")


private_app = Starlette(
    routes=[
        Route(
            "/change-password/",
            change_password(),
        ),
    ],
    middleware=[
        Middleware(
            AuthenticationMiddleware,
            on_error=on_auth_error,
            backend=SessionsAuthBackend(admin_only=False),
        ),
    ],
)


app = Starlette(
    routes=[
        Route("/", HomeEndpoint),
        Route("/login/", session_login()),
        Route(
            "/register/",
            register(redirect_to="/login/", user_defaults={"active": True}),
        ),
        Mount("/private/", private_app),
    ],
    middleware=[
        Middleware(CSRFMiddleware, allow_form_param=True),
    ],
)

If you want to use FastAPI instead, just make the following minor changes:

  • Change the imports from starlette -> fastapi

  • Change Starlette -> FastAPI

Source

piccolo_api.change_password.endpoints.change_password(login_url: str = '/login/', session_table: Type[SessionsBase] | None = SessionsBase, session_cookie_name: str | None = 'id', template_path: str | None = None, styles: Styles | None = None, read_only: bool = False) Type[ChangePasswordEndpoint][source]

An endpoint for changing passwords.

Parameters:
  • login_url – Where to redirect the user to after successfully changing their password.

  • session_table – If provided, when the password is changed, the sessions for the user will be invalidated in the database.

  • session_cookie_name – If provided, when the password is changed, the session cookie with this name will be deleted.

  • template_path – If you want to override the default change password HTML template, you can do so by specifying the absolute path to a custom template. For example '/some_directory/change_password.html'. Refer to the default template at piccolo_api/templates/change_password.html as a basis for your custom template.

  • styles – Modify the appearance of the HTML template using CSS.

Read_only:

If True, the endpoint only responds to GET requests. It’s not commonly needed, except when running demos.