1use std::fmt;
4use std::sync::Arc;
5
6use fastauth_core::AuthError;
7use fastauth_core::adapter::Adapter;
8use fastauth_core::error::ErrorCodes;
9use fastauth_core::plugin::{Plugin, PluginBuilder};
10use fastauth_core::value::Value;
11use http::StatusCode;
12
13use crate::http::{DynHttpClient, Http, HttpClient};
14use crate::provider::{DynProvider, OAuthProfile, OAuthProvider};
15use crate::routes::{LinkSocial, ListAccounts, SignInSocial, SocialCallback, UnlinkAccount};
16
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19pub enum AccountLinking {
20 #[default]
22 ByVerifiedEmail,
23 Off,
26}
27
28pub type MapProfile =
31 dyn Fn(&OAuthProfile, &str) -> Result<Vec<(&'static str, Value)>, AuthError> + Send + Sync;
32
33pub struct ConfiguredProvider {
36 pub(crate) provider: Arc<dyn DynProvider>,
37 pub(crate) map_profile: Option<Arc<MapProfile>>,
38 pub(crate) disable_sign_up: bool,
39}
40
41impl fmt::Debug for ConfiguredProvider {
42 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43 f.debug_struct("ConfiguredProvider")
44 .field("id", &self.provider.id())
45 .field("map_profile", &self.map_profile.is_some())
46 .field("disable_sign_up", &self.disable_sign_up)
47 .finish()
48 }
49}
50
51impl<P: OAuthProvider> From<P> for ConfiguredProvider {
52 fn from(provider: P) -> Self {
53 Self {
54 provider: Arc::new(provider),
55 map_profile: None,
56 disable_sign_up: false,
57 }
58 }
59}
60
61impl ConfiguredProvider {
62 pub fn map_profile<F>(mut self, map: F) -> Self
65 where
66 F: Fn(&OAuthProfile, &str) -> Result<Vec<(&'static str, Value)>, AuthError>
67 + Send
68 + Sync
69 + 'static,
70 {
71 self.map_profile = Some(Arc::new(map));
72 self
73 }
74
75 pub fn disable_sign_up(mut self, disable: bool) -> Self {
78 self.disable_sign_up = disable;
79 self
80 }
81}
82
83pub trait OAuthProviderExt: OAuthProvider + Sized {
85 fn map_profile<F>(self, map: F) -> ConfiguredProvider
87 where
88 F: Fn(&OAuthProfile, &str) -> Result<Vec<(&'static str, Value)>, AuthError>
89 + Send
90 + Sync
91 + 'static,
92 {
93 ConfiguredProvider::from(self).map_profile(map)
94 }
95
96 fn disable_sign_up(self, disable: bool) -> ConfiguredProvider {
98 ConfiguredProvider::from(self).disable_sign_up(disable)
99 }
100}
101
102impl<P: OAuthProvider> OAuthProviderExt for P {}
103
104pub struct Social {
106 pub(crate) providers: Vec<ConfiguredProvider>,
107 pub(crate) http: Arc<dyn DynHttpClient>,
108 pub(crate) account_linking: AccountLinking,
109 pub(crate) map_profile: Option<Arc<MapProfile>>,
110}
111
112impl fmt::Debug for Social {
113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114 f.debug_struct("Social")
115 .field("providers", &self.providers)
116 .field("account_linking", &self.account_linking)
117 .field("map_profile", &self.map_profile.is_some())
118 .finish_non_exhaustive()
119 }
120}
121
122#[cfg(feature = "reqwest")]
123impl Default for Social {
124 fn default() -> Self {
125 Self::new()
126 }
127}
128
129impl Social {
130 #[cfg(feature = "reqwest")]
132 pub fn new() -> Self {
133 Self::with_http_client(crate::http::ReqwestClient::new())
134 }
135
136 pub fn with_http_client(client: impl HttpClient) -> Self {
138 Self {
139 providers: Vec::new(),
140 http: Arc::new(client),
141 account_linking: AccountLinking::default(),
142 map_profile: None,
143 }
144 }
145
146 pub fn provider(mut self, provider: impl Into<ConfiguredProvider>) -> Self {
149 let provider = provider.into();
150 self.providers
151 .retain(|p| p.provider.id() != provider.provider.id());
152 self.providers.push(provider);
153 self
154 }
155
156 pub fn map_profile<F>(mut self, map: F) -> Self
165 where
166 F: Fn(&OAuthProfile, &str) -> Result<Vec<(&'static str, Value)>, AuthError>
167 + Send
168 + Sync
169 + 'static,
170 {
171 self.map_profile = Some(Arc::new(map));
172 self
173 }
174
175 pub fn account_linking(mut self, linking: AccountLinking) -> Self {
176 self.account_linking = linking;
177 self
178 }
179
180 pub(crate) fn find(&self, id: &str) -> Option<&ConfiguredProvider> {
181 self.providers.iter().find(|p| p.provider.id() == id)
182 }
183
184 pub(crate) fn http(&self) -> Http<'_> {
185 Http::from_dyn(&*self.http)
186 }
187}
188
189impl Plugin for Social {
190 const ID: &'static str = "social";
191 type Requires = ();
192 type UserFields = ();
193 type SessionFields = ();
194
195 fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
196 app.endpoint(SignInSocial(self.clone()))
197 .endpoint(SocialCallback(self.clone()))
198 .endpoint(LinkSocial(self.clone()))
199 .endpoint(ListAccounts)
200 .endpoint(UnlinkAccount)
201 .errors::<SocialError>();
202 }
203}
204
205#[derive(Clone, Copy, Debug, PartialEq, Eq)]
208pub enum SocialError {
209 ProviderNotFound,
211 AccountNotFound,
213 LastAccount,
215}
216
217impl From<SocialError> for AuthError {
218 fn from(err: SocialError) -> Self {
219 match err {
220 SocialError::ProviderNotFound => AuthError::new(
221 StatusCode::NOT_FOUND,
222 "PROVIDER_NOT_FOUND",
223 "provider not found",
224 ),
225 SocialError::AccountNotFound => AuthError::new(
226 StatusCode::BAD_REQUEST,
227 "ACCOUNT_NOT_FOUND",
228 "account not found",
229 ),
230 SocialError::LastAccount => AuthError::new(
231 StatusCode::BAD_REQUEST,
232 "FAILED_TO_UNLINK_LAST_ACCOUNT",
233 "you can't unlink your last account",
234 ),
235 }
236 }
237}
238
239impl ErrorCodes for SocialError {
240 const CODES: &'static [&'static str] = &[
241 "PROVIDER_NOT_FOUND",
242 "ACCOUNT_NOT_FOUND",
243 "FAILED_TO_UNLINK_LAST_ACCOUNT",
244 ];
245}