Pages for signed-in members
An extractor reads the signed-in member from the session, so a handler that takes it runs only for a signed-in visitor. Anyone else gets a redirect to the sign-in page from a page, and a 401 from an action.
The signed-in member
Member below is an axum extractor: it implements FromRequestParts<AppState>, reads the Session, and finds the name the sign-in put there. A handler that takes it, as home(state, member: Member, ()), runs only for a signed-in visitor, and the extractor's rejection is the answer to everyone else. The repository's auth example uses the same extractor:
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use hypersig::{PageResponse, RequestKind};
use tower_sessions::Session;
/// The member whose session cookie came with the request.
struct Member {
name: String,
}
impl FromRequestParts<AppState> for Member {
type Rejection = Response;
async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, Response> {
let session = Session::from_request_parts(parts, state)
.await
.map_err(IntoResponse::into_response)?;
match session.get::<String>(MEMBER).await {
Ok(Some(name)) => Ok(Self { name }),
// A page goes to the sign-in page. An action's `fetch` would
// follow a redirect, so it gets a 401 its `Call::error` shows.
Ok(None) => Err(if RequestKind::of(parts) == RequestKind::Navigation {
PageResponse::redirect(LOGIN.url(())).into_response()
} else {
(StatusCode::UNAUTHORIZED, "Sign in again.").into_response()
}),
Err(error) => Err(StoreFailed(error).into_response()),
}
}
}
#[derive(Signals, Serialize, Deserialize)]
struct Home {
name: String,
draft: String,
problem: String,
/// The status of the last failed call, or `0`.
failure: i32,
}
async fn home(_: AppState, member: Member, (): ()) -> Page<Home> {
let signals = Home {
name: member.name,
draft: String::new(),
problem: String::new(),
failure: 0,
};
let signed_out = Home::failure().equals(i32::from(StatusCode::UNAUTHORIZED.as_u16()));
Page::new("Home", signals).child(
form()
.on_submit(
ADD_NOTE
.call_with(Home::draft())
.error(Home::problem())
.status(Home::failure()),
)
.child(input().bind(Home::draft()))
.child(button().text("Add note"))
.child(p().bind_text(Home::problem()))
.child(a().show(signed_out).href(LOGIN.link()).text("Sign in again")),
)
}
async fn add_note(state: AppState, member: Member, note: String) -> Patches<Home> {
state.save(&member.name, note);
Home::draft().patch(String::new()).into()
}
hypersig::routes! {
fn pages(Router<AppState>);
const HOME: Route = "/" => home;
const LOGIN: Route = "/login" => login;
action ADD_NOTE: Action<Home, String> = post "/notes" => add_note;
}A redirect for a page, a 401 for an action
RequestKind::of is fn of(request: &Parts) -> RequestKind. It returns RequestKind::Runtime for a request the runtime sends to call an action, a stream, or an upload, and RequestKind::Navigation for a browser loading a page. The extractor answers each kind differently:
| Request | Answer without a member |
|---|---|
GET /, the browser loading the page | 303 See Other with location: /login |
POST /notes, the runtime calling the action | 401 Unauthorized with the text/plain body Sign in again. |
An action gets no redirect because the runtime's fetch would follow it and receive the sign-in page's HTML, which it cannot apply as patches. The 401's text reaches the signal the call's error names. axum-login's login_required! answers every request it guards in one way, a redirect or a 401, chosen when the router is built, so the sample writes its own extractor.
The address of the sign-in page
PageResponse::redirect is fn redirect(url: Url) -> PageResponse, and answers with a 303 See Other to url. As with Patches::navigate, the Url comes from a route, as LOGIN.url(()), so a path written as a string fails to compile with E0308. Links and redirects covers the redirect in general.
use hypersig::{PageResponse, RequestKind};
fn signed_out(kind: RequestKind) -> Response {
if kind == RequestKind::Navigation {
// `redirect` takes a `Url`, which only a route's `url` builds.
PageResponse::redirect("/login").into_response()
} else {
"Sign in again.".into_response()
}
}A link to sign in again
A visitor whose session ended while the page was open gets the 401 on the next call. Call::status is fn status(self, status: Sig<S, i32>) -> Self: it sets the signal to 0 when the call is sent and to the status of a failed answer. The home page above compares failure with StatusCode::UNAUTHORIZED and shows a link to the sign-in page while they are equal, as the auth example does. The link is in the HTML from the start, hidden while the condition is false.
The status stays 0 when no answer the runtime can read arrives, such as when the connection fails, so the link appears only for a 401.
What the types leave unchecked
Nothing makes a handler take Member. A page or an action whose handler leaves it out is served to every visitor, signed in or not, so list the handlers that take it when you review a change to routes!. The key MEMBER and the type String that session.get reads are not checked against what the sign-in inserted either. A different key reads None, and the visitor is sent to the sign-in page after signing in. A value that does not deserialize as the type is an error, which the extractor answers with a 500.
Next
- Signing in writes the member's name into the session this extractor reads.
- Extractors and headers covers extractors in general.
- Security lists what the router refuses before a handler runs.