Skip to main content

aurelin_framework/authorization/
response.rs

1use axum::{
2    http::StatusCode,
3    response::{IntoResponse, Response},
4};
5
6/// The result of evaluating an authorization ability.
7#[derive(Clone, Debug, Eq, PartialEq)]
8pub struct AuthorizationResponse {
9    allowed: bool,
10    message: Option<String>,
11    code: Option<String>,
12    status: Option<StatusCode>,
13}
14
15impl AuthorizationResponse {
16    /// Allow the requested action.
17    pub fn allow() -> Self {
18        Self { allowed: true, message: None, code: None, status: None }
19    }
20
21    /// Deny the requested action with the default HTTP status.
22    pub fn deny() -> Self {
23        Self { allowed: false, message: None, code: None, status: None }
24    }
25
26    /// Deny the requested action with a particular HTTP status.
27    pub fn deny_with_status(status: StatusCode) -> Self {
28        Self::deny().with_status(status)
29    }
30
31    /// Conceal a denied resource behind a not-found response.
32    pub fn deny_as_not_found() -> Self {
33        Self::deny_with_status(StatusCode::NOT_FOUND)
34    }
35
36    /// Attach a user-facing denial message.
37    pub fn with_message(mut self, message: impl Into<String>) -> Self {
38        self.message = Some(message.into());
39        self
40    }
41
42    /// Attach an application-defined denial reason code.
43    pub fn with_code(mut self, code: impl Into<String>) -> Self {
44        self.code = Some(code.into());
45        self
46    }
47
48    /// Set the HTTP status used when this response is denied.
49    pub fn with_status(mut self, status: StatusCode) -> Self {
50        self.status = Some(status);
51        self
52    }
53
54    /// Whether the action was allowed.
55    pub fn allowed(&self) -> bool {
56        self.allowed
57    }
58
59    /// Whether the action was denied.
60    pub fn denied(&self) -> bool {
61        !self.allowed
62    }
63
64    /// The optional user-facing message.
65    pub fn message(&self) -> Option<&str> {
66        self.message.as_deref()
67    }
68
69    /// The optional application-defined reason code.
70    pub fn code(&self) -> Option<&str> {
71        self.code.as_deref()
72    }
73
74    /// The explicitly selected HTTP status, if any.
75    pub fn status(&self) -> Option<StatusCode> {
76        self.status
77    }
78
79    /// Return an error when this response denies the action.
80    pub fn authorize(self) -> Result<Self, AuthorizationError> {
81        if self.allowed() { Ok(self) } else { Err(AuthorizationError::Denied(self)) }
82    }
83}
84
85/// Convert a policy result into an authorization response.
86pub trait IntoAuthorizationResponse {
87    fn into_authorization_response(self) -> AuthorizationResponse;
88
89    #[doc(hidden)]
90    fn into_on_demand_response(self, _allow_when: bool) -> AuthorizationResponse
91    where
92        Self: Sized,
93    {
94        self.into_authorization_response()
95    }
96}
97
98impl IntoAuthorizationResponse for AuthorizationResponse {
99    fn into_authorization_response(self) -> AuthorizationResponse {
100        self
101    }
102}
103
104impl IntoAuthorizationResponse for bool {
105    fn into_authorization_response(self) -> AuthorizationResponse {
106        if self { AuthorizationResponse::allow() } else { AuthorizationResponse::deny() }
107    }
108
109    fn into_on_demand_response(self, allow_when: bool) -> AuthorizationResponse {
110        (self == allow_when).into_authorization_response()
111    }
112}
113
114/// An authorization denial or invalid gate invocation.
115#[derive(Debug, thiserror::Error)]
116pub enum AuthorizationError {
117    /// The gate or policy denied the action.
118    #[error("{message}", message = denial_message(.0))]
119    Denied(AuthorizationResponse),
120    /// The ability was invoked with the wrong context type.
121    #[error(transparent)]
122    Gate(#[from] super::GateError),
123}
124
125impl AuthorizationError {
126    /// The authorization response associated with a denial.
127    pub fn response(&self) -> Option<&AuthorizationResponse> {
128        match self {
129            Self::Denied(response) => Some(response),
130            Self::Gate(_) => None,
131        }
132    }
133}
134
135impl IntoResponse for AuthorizationError {
136    fn into_response(self) -> Response {
137        match self {
138            Self::Denied(response) => {
139                let status = response.status.unwrap_or(StatusCode::FORBIDDEN);
140                let message = denial_message(&response).to_owned();
141                (status, message).into_response()
142            }
143            Self::Gate(error) => {
144                tracing::error!(error = %error, "authorization gate invocation failed");
145                (StatusCode::INTERNAL_SERVER_ERROR, "Internal server error").into_response()
146            }
147        }
148    }
149}
150
151fn denial_message(response: &AuthorizationResponse) -> &str {
152    response.message.as_deref().unwrap_or("This action is unauthorized.")
153}