use std::sync::Arc;
use actix_web::{HttpResponse, Result as ActixResult, web, http::StatusCode};
use serde::Serialize;
use crate::OAuthConfig;
use crate::error::OAuthError;
use crate::grants::{self, TokenRequest};
pub fn configure_oauth(cfg: &mut web::ServiceConfig, config: Arc<OAuthConfig>) {
cfg.app_data(web::Data::new(config))
.route("/oauth/token", web::post().to(token_endpoint));
}
async fn token_endpoint(
config: web::Data<Arc<OAuthConfig>>,
request: web::Json<TokenRequest>,
) -> ActixResult<HttpResponse> {
let response = grants::issue_token(&config, request.into_inner());
let http_response = match response {
Ok(token) => HttpResponse::Ok().json(token),
Err(err) => HttpResponse::build(StatusCode::from_u16(err.status_code().into()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)).json(ErrorBody::from(&err)),
};
Ok(http_response)
}
#[derive(Serialize)]
struct ErrorBody {
error: String,
#[serde(skip_serializing_if = "Option::is_none")]
error_description: Option<String>,
}
impl From<&OAuthError> for ErrorBody {
fn from(err: &OAuthError) -> Self {
let error = match err {
OAuthError::InvalidClient => "invalid_client",
OAuthError::UnsupportedGrant(_) | OAuthError::NotImplemented(_) => {
"unsupported_grant_type"
}
OAuthError::InvalidGrant(_) => "invalid_grant",
OAuthError::InvalidScope(_) => "invalid_scope",
OAuthError::Config(_) | OAuthError::TokenStore(_) | OAuthError::Internal(_) => {
"server_error"
}
}
.to_string();
let error_description = match err {
OAuthError::UnsupportedGrant(message)
| OAuthError::InvalidGrant(message)
| OAuthError::InvalidScope(message)
| OAuthError::Internal(message) => Some(message.clone()),
OAuthError::NotImplemented(message) => Some((*message).into()),
_ => None,
};
Self {
error,
error_description,
}
}
}