Skip to main content

User

Struct User 

Source
#[non_exhaustive]
pub struct User { /* private fields */ }
Expand description

Who a request to a route of your own is, authenticated as REST does.

use axum::{extract::State, Json};
use postrust_server::{AppState, User};
use serde_json::{json, Value};
use std::sync::Arc;

async fn summary(
    user: User,
    State(state): State<Arc<AppState>>,
) -> Result<Json<Value>, postrust_server::Error> {
    let mut tx = state.begin_as(&user).await?;
    let n: i64 = sqlx::query_scalar("select count(*) from todos")
        .fetch_one(&mut *tx)
        .await?;
    tx.commit().await?;
    Ok(Json(json!({ "todos": n })))
}

As an extractor, User reads the Authorization header. A request with no token is the anonymous role (PGRST_DB_ANON_ROLE), or refused with PostgREST’s 401 where there is none; a token that does not verify is refused with the status and body the API gives it – PGRST301, PGRST303 and the rest, with the WWW-Authenticate challenge.

§Option<User>

Option<User> is for a route that does something different for a caller who has not signed in, whatever the server’s anonymous role: it is None when the request sends no Authorization header at all, and Some with the token’s user when it sends one that verifies. A token that does not verify is still refused, not read as None: a client whose token has expired should be told so, not quietly answered as somebody else. A route that wants the anonymous role for a request with no token takes User itself; see User::is_anonymous.

§What else it carries

What REST tells the database about a request besides who sent it, so that a policy or function reading request.headers, request.cookies, request.method, request.path or request.trace_id sees the same thing in a transaction of yours that it sees in REST’s:

  • the method, and the path as the client sent it – with the prefix your router was nested at, where REST’s request.path is without /api, since that prefix is the API’s mount rather than part of the resource;
  • every header, by its lowercase name, and the cookies;
  • the trace the request belongs to, from the server’s request span.

Not the schema a Accept-Profile header names, nor the time zone a Prefer: timezone asks for: those are REST’s request syntax, and a route of yours has its own. Its transaction’s search_path starts at the default schema.

Implementations§

Source§

impl User

Source

pub fn role(&self) -> &str

The database role the request runs as: the token’s role claim, or the anonymous role.

Source

pub fn claims(&self) -> &HashMap<String, Value>

The token’s claims, every one of them, as request.jwt.claims carries them. Empty for an anonymous request.

Source

pub fn claim(&self, name: &str) -> Option<&Value>

One of the token’s claims, where it has it.

Source

pub fn is_anonymous(&self) -> bool

Whether the request sent no token, and runs as the anonymous role.

Source

pub fn trace_id(&self) -> Option<TraceId>

The trace the request belongs to, where the server’s request span gave it one.

Trait Implementations§

Source§

impl Clone for User

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for User

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl FromRequestParts<Arc<AppState>> for User

Source§

type Rejection = Error

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

async fn from_request_parts( parts: &mut Parts, state: &Arc<AppState>, ) -> Result<Self, Self::Rejection>

Perform the extraction.
Source§

impl OptionalFromRequestParts<Arc<AppState>> for User

Source§

type Rejection = Error

If the extractor fails, it will use this “rejection” type. Read more
Source§

async fn from_request_parts( parts: &mut Parts, state: &Arc<AppState>, ) -> Result<Option<Self>, Self::Rejection>

Perform the extraction.

Auto Trait Implementations§

§

impl Freeze for User

§

impl RefUnwindSafe for User

§

impl Send for User

§

impl Sync for User

§

impl Unpin for User

§

impl UnsafeUnpin for User

§

impl UnwindSafe for User

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<S, T> FromRequest<S, ViaParts> for T
where S: Send + Sync, T: FromRequestParts<S>,

Source§

type Rejection = <T as FromRequestParts<S>>::Rejection

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

fn from_request( req: Request<Body>, state: &S, ) -> impl Future<Output = Result<T, <T as FromRequest<S, ViaParts>>::Rejection>>

Perform the extraction.
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> MaybeSend for T
where T: Send + ?Sized,

Source§

impl<T> MaybeSendSync for T
where T: Send + Sync + ?Sized,

Source§

impl<T> MaybeSync for T
where T: Sync + ?Sized,

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more