use std::fmt;
use std::sync::Arc;
use fastauth_core::AuthError;
use fastauth_core::adapter::Adapter;
use fastauth_core::error::ErrorCodes;
use fastauth_core::plugin::{Plugin, PluginBuilder};
use fastauth_core::value::Value;
use http::StatusCode;
use crate::http::{DynHttpClient, Http, HttpClient};
use crate::provider::{DynProvider, OAuthProfile, OAuthProvider};
use crate::routes::{LinkSocial, ListAccounts, SignInSocial, SocialCallback, UnlinkAccount};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AccountLinking {
#[default]
ByVerifiedEmail,
Off,
}
pub type MapProfile =
dyn Fn(&OAuthProfile, &str) -> Result<Vec<(&'static str, Value)>, AuthError> + Send + Sync;
pub struct ConfiguredProvider {
pub(crate) provider: Arc<dyn DynProvider>,
pub(crate) map_profile: Option<Arc<MapProfile>>,
pub(crate) disable_sign_up: bool,
}
impl fmt::Debug for ConfiguredProvider {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ConfiguredProvider")
.field("id", &self.provider.id())
.field("map_profile", &self.map_profile.is_some())
.field("disable_sign_up", &self.disable_sign_up)
.finish()
}
}
impl<P: OAuthProvider> From<P> for ConfiguredProvider {
fn from(provider: P) -> Self {
Self {
provider: Arc::new(provider),
map_profile: None,
disable_sign_up: false,
}
}
}
impl ConfiguredProvider {
pub fn map_profile<F>(mut self, map: F) -> Self
where
F: Fn(&OAuthProfile, &str) -> Result<Vec<(&'static str, Value)>, AuthError>
+ Send
+ Sync
+ 'static,
{
self.map_profile = Some(Arc::new(map));
self
}
pub fn disable_sign_up(mut self, disable: bool) -> Self {
self.disable_sign_up = disable;
self
}
}
pub trait OAuthProviderExt: OAuthProvider + Sized {
fn map_profile<F>(self, map: F) -> ConfiguredProvider
where
F: Fn(&OAuthProfile, &str) -> Result<Vec<(&'static str, Value)>, AuthError>
+ Send
+ Sync
+ 'static,
{
ConfiguredProvider::from(self).map_profile(map)
}
fn disable_sign_up(self, disable: bool) -> ConfiguredProvider {
ConfiguredProvider::from(self).disable_sign_up(disable)
}
}
impl<P: OAuthProvider> OAuthProviderExt for P {}
pub struct Social {
pub(crate) providers: Vec<ConfiguredProvider>,
pub(crate) http: Arc<dyn DynHttpClient>,
pub(crate) account_linking: AccountLinking,
pub(crate) map_profile: Option<Arc<MapProfile>>,
}
impl fmt::Debug for Social {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Social")
.field("providers", &self.providers)
.field("account_linking", &self.account_linking)
.field("map_profile", &self.map_profile.is_some())
.finish_non_exhaustive()
}
}
#[cfg(feature = "reqwest")]
impl Default for Social {
fn default() -> Self {
Self::new()
}
}
impl Social {
#[cfg(feature = "reqwest")]
pub fn new() -> Self {
Self::with_http_client(crate::http::ReqwestClient::new())
}
pub fn with_http_client(client: impl HttpClient) -> Self {
Self {
providers: Vec::new(),
http: Arc::new(client),
account_linking: AccountLinking::default(),
map_profile: None,
}
}
pub fn provider(mut self, provider: impl Into<ConfiguredProvider>) -> Self {
let provider = provider.into();
self.providers
.retain(|p| p.provider.id() != provider.provider.id());
self.providers.push(provider);
self
}
pub fn map_profile<F>(mut self, map: F) -> Self
where
F: Fn(&OAuthProfile, &str) -> Result<Vec<(&'static str, Value)>, AuthError>
+ Send
+ Sync
+ 'static,
{
self.map_profile = Some(Arc::new(map));
self
}
pub fn account_linking(mut self, linking: AccountLinking) -> Self {
self.account_linking = linking;
self
}
pub(crate) fn find(&self, id: &str) -> Option<&ConfiguredProvider> {
self.providers.iter().find(|p| p.provider.id() == id)
}
pub(crate) fn http(&self) -> Http<'_> {
Http::from_dyn(&*self.http)
}
}
impl Plugin for Social {
const ID: &'static str = "social";
type Requires = ();
type UserFields = ();
type SessionFields = ();
fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
app.endpoint(SignInSocial(self.clone()))
.endpoint(SocialCallback(self.clone()))
.endpoint(LinkSocial(self.clone()))
.endpoint(ListAccounts)
.endpoint(UnlinkAccount)
.errors::<SocialError>();
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SocialError {
ProviderNotFound,
AccountNotFound,
LastAccount,
}
impl From<SocialError> for AuthError {
fn from(err: SocialError) -> Self {
match err {
SocialError::ProviderNotFound => AuthError::new(
StatusCode::NOT_FOUND,
"PROVIDER_NOT_FOUND",
"provider not found",
),
SocialError::AccountNotFound => AuthError::new(
StatusCode::BAD_REQUEST,
"ACCOUNT_NOT_FOUND",
"account not found",
),
SocialError::LastAccount => AuthError::new(
StatusCode::BAD_REQUEST,
"FAILED_TO_UNLINK_LAST_ACCOUNT",
"you can't unlink your last account",
),
}
}
}
impl ErrorCodes for SocialError {
const CODES: &'static [&'static str] = &[
"PROVIDER_NOT_FOUND",
"ACCOUNT_NOT_FOUND",
"FAILED_TO_UNLINK_LAST_ACCOUNT",
];
}