use actix_web::{HttpRequest, HttpResponse, http::header, web};
use serde::Deserialize;
use serde_json::json;
use authr_core::{context::AuthrContext, database::AuthDatabase};
use authr_operations::{
account::{
AccountSummary, CallbackLinkSocialAccountInput, CallbackLinkSocialAccountResult,
callback_link_social_account,
},
auth::{
MetadataConfig,
oauth::{
OAuthCallbackInput, OAuthCallbackResult, SignInSocialInput,
callback as callback_operation, sign_in_social as sign_in_social_operation,
},
},
};
use crate::{
cookies::{
build_oauth_binding_cookie, build_removal_oauth_binding_cookie, build_session_cookie,
oauth_binding_cookie_name,
},
error::ServerError,
utils::{OAuthCallbackFlow, get_provider_callback_url, identify_oauth_callback},
};
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SignInSocialRequest {
provider: String,
callback_url: Option<String>,
#[serde(default)]
disable_redirect: bool,
scopes: Option<Vec<String>>,
}
#[tracing::instrument(
name = "auth.sign_in_social",
skip_all,
fields(
provider = %body.provider,
disable_redirect = body.disable_redirect,
has_callback_url = body.callback_url.is_some(),
has_custom_scopes = body.scopes.is_some()
),
err
)]
pub async fn sign_in_social<D: AuthDatabase + 'static>(
req: HttpRequest,
ctx: web::Data<AuthrContext<D>>,
body: web::Json<SignInSocialRequest>,
) -> Result<HttpResponse, ServerError> {
if let Some(callback_url) = body.callback_url.as_deref() {
if !ctx.config().base_url.is_allowed(callback_url) {
return Err(ServerError::InvalidCallbackUrl);
}
}
let redirect_uri = get_provider_callback_url(
&ctx.config().base_url,
&ctx.config().base_path,
&req,
&body.provider,
)?;
let result = sign_in_social_operation(
&ctx,
SignInSocialInput {
provider_id: body.provider.clone(),
callback_url: body.callback_url.clone(),
redirect_uri,
scopes: body.scopes.clone(),
},
)
.await?;
let binding_cookie = build_oauth_binding_cookie(&result.state, result.browser_binding_token);
if body.disable_redirect {
return Ok(HttpResponse::Ok().cookie(binding_cookie).json(json!({
"url": result.authorization_url,
})));
}
Ok(HttpResponse::Found()
.append_header((header::LOCATION, result.authorization_url.to_string()))
.cookie(binding_cookie)
.finish())
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct OAuthCallbackQuery {
pub code: Option<String>,
pub error: Option<String>,
pub error_description: Option<String>,
pub state: Option<String>,
}
#[tracing::instrument(
name = "auth.oauth_callback",
skip_all,
fields(
provider = %path.as_str(),
has_code = query.code.is_some(),
has_state = query.state.is_some()
),
err
)]
pub async fn callback<D: AuthDatabase + 'static>(
req: HttpRequest,
query: web::Query<OAuthCallbackQuery>,
ctx: web::Data<AuthrContext<D>>,
path: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
let provider_id = path.into_inner();
let query = query.into_inner();
let state = query
.state
.as_deref()
.ok_or(ServerError::InvalidCallbackUrl)?;
let redirect_uri = get_provider_callback_url(
&ctx.config().base_url,
&ctx.config().base_path,
&req,
&provider_id,
)?;
let ip_address = {
let connection = req.connection_info();
connection.realip_remote_addr().map(str::to_owned)
};
let user_agent = req
.headers()
.get(header::USER_AGENT)
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let flow = identify_oauth_callback(ctx.get_ref(), state).await?;
let binding_cookie_name = oauth_binding_cookie_name(state);
let browser_binding_token = req
.cookie(&binding_cookie_name)
.map(|cookie| cookie.value().to_owned());
match flow {
OAuthCallbackFlow::SignIn => {
let result = callback_operation(
&ctx,
OAuthCallbackInput {
provider_id,
code: query.code,
error: query.error,
error_description: query.error_description,
state: Some(state.to_owned()),
redirect_uri,
browser_binding_token,
},
MetadataConfig {
ip_address,
user_agent,
},
)
.await?;
match result {
OAuthCallbackResult::Authenticated {
callback_url,
user: _,
session,
} => Ok(HttpResponse::Found()
.append_header((header::LOCATION, callback_url))
.cookie(build_session_cookie(&session))
.cookie(build_removal_oauth_binding_cookie(state))
.finish()),
OAuthCallbackResult::RedirectError { error, description } => {
Ok(HttpResponse::BadRequest()
.cookie(build_removal_oauth_binding_cookie(state))
.json(json!({
"error": error,
"errorDescription": description,
})))
}
}
}
OAuthCallbackFlow::LinkAccount => {
let result = callback_link_social_account(
&ctx,
CallbackLinkSocialAccountInput {
provider_id,
code: query.code,
error: query.error,
error_description: query.error_description,
state: state.to_owned(),
redirect_uri,
browser_binding_token,
},
)
.await?;
match result {
CallbackLinkSocialAccountResult::Linked {
account,
callback_url,
} => {
if let Some(callback_url) = callback_url {
Ok(HttpResponse::Found()
.append_header((header::LOCATION, callback_url))
.cookie(build_removal_oauth_binding_cookie(state))
.finish())
} else {
Ok(HttpResponse::Ok()
.cookie(build_removal_oauth_binding_cookie(state))
.json(json!({
"status": true,
"accounts": AccountSummary::from(&account),
})))
}
}
CallbackLinkSocialAccountResult::ProviderError {
callback_url,
error,
description,
} => {
if let Some(callback_url) = callback_url {
let mut url =
url::Url::parse(&callback_url).map_err(|_| ServerError::Internal)?;
url.query_pairs_mut().append_pair("error", &error);
if let Some(description) = description.as_deref() {
url.query_pairs_mut()
.append_pair("error_description", description);
}
Ok(HttpResponse::Found()
.cookie(build_removal_oauth_binding_cookie(state))
.append_header((header::LOCATION, url.to_string()))
.finish())
} else {
Ok(HttpResponse::BadRequest()
.cookie(build_removal_oauth_binding_cookie(state))
.json(json!({
"error": error,
"errorDescription": description,
})))
}
}
}
}
}
}