use tide_017::{Request, Response, StatusCode};
use sa_token_core::{token::TokenValue, error::messages};
use serde_json::json;
#[derive(Debug)]
pub struct AuthError;
impl AuthError {
pub fn new() -> Self {
Self
}
pub fn message(&self) -> &'static str {
messages::AUTH_ERROR
}
pub fn to_json(&self) -> String {
json!({
"code": 401,
"message": self.message()
}).to_string()
}
pub fn to_response(&self) -> Response {
let mut res = Response::new(StatusCode::Unauthorized);
res.set_body(self.to_json());
res.set_content_type("application/json");
res
}
}
impl Default for AuthError {
fn default() -> Self {
Self::new()
}
}
pub struct SaTokenExtractor(pub TokenValue);
impl SaTokenExtractor {
pub fn token(&self) -> &TokenValue {
&self.0
}
pub fn from_request<State: Clone + Send + Sync + 'static>(req: &Request<State>) -> Result<Self, AuthError> {
req.ext::<TokenValue>()
.cloned()
.map(SaTokenExtractor)
.ok_or_else(AuthError::new)
}
}
pub struct OptionalSaTokenExtractor(pub Option<TokenValue>);
impl OptionalSaTokenExtractor {
pub fn token(&self) -> Option<&TokenValue> {
self.0.as_ref()
}
pub fn from_request<State: Clone + Send + Sync + 'static>(req: &Request<State>) -> Self {
let token = req.ext::<TokenValue>().cloned();
OptionalSaTokenExtractor(token)
}
}
pub struct LoginIdExtractor(pub String);
impl LoginIdExtractor {
pub fn login_id(&self) -> &str {
&self.0
}
pub fn from_request<State: Clone + Send + Sync + 'static>(req: &Request<State>) -> Result<Self, AuthError> {
req.ext::<String>()
.cloned()
.map(LoginIdExtractor)
.ok_or_else(AuthError::new)
}
}